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?
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