【问题标题】:Why can't .NET mock frameworks use new to hide non-virtual methods for non-sealed classes?为什么.NET 模拟框架不能使用 new 来隐藏非密封类的非虚拟方法?
【发布时间】:2011-09-01 06:49:12
【问题描述】:

例如:

public class ThirdPartyClass
{
    public void DoSomething() { ... }
}

// Mock framework generated class
public class MockThirdPartyClass : ThirdPartyClass
{
    public new void DoSomething() { // Mock user's deletegate goes here }
}

我怀疑问题是被测类使用基类作为其变量/参数,因此对模拟类的方法的调用转到基版本而不是影子版本:

public class MyClass
{
    private ThirdPartyClass tpc;

    public MyClass() { }

    public MyClass(ThirdPartyClass tpc)
    {            
        this.tpc = tpc;
    }

    public void MyClassDoesSomething()
    {
        this.tpc.DoSomething(); // Bypasses MockThirdPartyClass shadow method
    }

这是正确的吗?

【问题讨论】:

    标签: .net class frameworks mocking concrete


    【解决方案1】:

    是的,没错。

    被测类永远不会引用代理类 - 它总是会引用代理的基类(即真实类)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2022-09-25
      • 1970-01-01
      • 2019-09-24
      • 2011-09-25
      • 1970-01-01
      • 2012-07-29
      相关资源
      最近更新 更多