Moq requirements? Defeats the purpose?

柔情痞子 提交于 2019-12-06 00:35:55

Your question is very valid but if you think about it,there is no other way to mock a class. If you take an interface, it's just a contract so the mock framework can mock how ever you want it but if you take a class, it already has an implementation for it's members.

So the mock framework, in order to be able to mock the class members, has to inherit from the class and override the member's behavior as requested and for this purpose only virtual members will work.

For eg. if you have (I'm showing methods but the same is true for properties)

class Foo
{
    public void Bar()
    {

    }
    public virtual void  virtualBar()
    {

    }
}

then the mock framework probably creates something like this to mock

public class MockFoo : Foo
{
    public override void virtualBar()
    {
        // mockery action
    }

    public new void Bar()
    {
        // mockery action
    }
}

Now when you have

Foo foo = GetMockObject(); // you get an instance of MockFoo

now when you call

foo.Bar();

you don't intend for it to call the actual implementation but since it's a non virtual member, it will call the Foo's Bar()

on the other hand, calling

foo.VirtualBar();

would call MockFoo's VirtualBar() as it's a virtual member which would have the behavior injected by the mock framework as requested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!