开发者

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

开发者 https://www.devze.com 2023-04-02 04:50 出处:网络
For example: public class ThirdPartyClass { public void DoSomething() { ... } } // Mock framework generated class

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

精彩评论

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

关注公众号