开发者

Why can't .NET mock frameworks use new to hide non-virtual methods for non-sealed classes?

For example:

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

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

I suspect the issue is that the class under test uses the base class for its variables/parameters, and hence calls to the mocked class' method go to the base version instead of the shadow version:

public class MyClass
{
    private ThirdPartyClass tpc;

    public MyClass() { }

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

    public void MyClassDoesSomething()
    {
        this.tpc.DoSomething(); // Bypasses MockThirdPartyClass shadow met开发者_运维技巧hod
    }

Is this correct?


Yes, that's correct.

The class under test is never going to refer to the Proxy class - it's always going to refer to the base class of the proxy (i.e. the real class).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜