Moq requirements? Defeats the purpose?

隐身守侯 提交于 2020-01-02 07:32:45

问题


Doesn't being required to virtualize all property accessors you want to mock kind of defeat the purpose of mocking?

I mean, if I have to modify my object and virtualize every single accesor I want to mock, couldn't I just as well inherit my class and mock it myself?


回答1:


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.



来源:https://stackoverflow.com/questions/5877546/moq-requirements-defeats-the-purpose

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