Moq requirements? Hit the target?

Is it necessary to virtualize all the property accessors that you want to scoff at in order to defeat the ridicule?

I mean, if I need to change my object and virtualize every single accessory that I want to make fun of, could I just inherit my class and mock it myself?

+3
source share
1 answer

Your question is very important, but if you think about it, there is no other way to mock the class. If you take the interface, itโ€™s just a contract, so the mock-up framework can make fun of the way you want, but if you take the class, it already has an implementation for it.

Thus, in order to be able to make fun of class members, the mock framework must inherit from the class and redefine the behavior of the member in accordance with the request, and only virtual members will work for this purpose.

For example, if you have (I show methods, but the same is true for properties)

class Foo { public void Bar() { } public virtual void virtualBar() { } } 

then the breadboard 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 that you have

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

now when you call

 foo.Bar(); 

you are not going to name its actual implementation, but since it is not a virtual member, it is called Foo Bar()

on the other hand causing

 foo.VirtualBar(); 

will call MockFoo VirtualBar() as it is a virtual member that will have the behavior introduced by the mock infrastructure upon request.

+3
source

All Articles