When can we mock an object and its methods?

I am new to Moq and unit testing. I have to write unit tests for many classes that have objects of other classes. Can I mock the methods of class objects. Here is the exact scenerio -

I have class 2 of classes A and B and A has a private object B and in method A I internally call method B and then do some calculations and return the result. Can I poke fun at method B in this scenerio? Please try to give me full information about the conditions in which I can mock class methods and functions. Thanx

+2


a source to share


1 answer


Yes, you can mock B methods.

The easiest way to do this is probably to pass an instance of B to A's constructor when you create it.

So in your unit tests, you can simply create mock B and pass it instead. Typically, you can easily compose any object that you pass or set from outside the object. So, everything that is passed to the constructor or set in the property. It's probably possible to mock private variables, although I don't know enough about Moq to be sure, but it's often best done by refactoring your code so that a dependent object is passed in instead.

If B implements the interface, IB, then you would do something like this:



var mockB = new Mock<IB>();
mockB.Setup(x => x.SomeMethod()).Returns([whatever value you want to return]);
var a = new A(mockB.Object);

      

Note. This code is C # and out of memory, so it might be wrong. This is a more general idea.

After that, you can call your method on a, which will use whatever value you put in the Returns method to customize to do its calculations.

+1


a source







All Articles