Unit Testing: Mocking Base Class Methods With Moq

15 Flares Twitter 2 Facebook 0 StumbleUpon 12 Google+ 1 LinkedIn 0 15 Flares ×

Yesterday I had to give someone a hand with a bit of unit testing where we had a fairly complex base class where we really wanted to mock out some of the base class methods. I used a solution which I had used before but it took me a while to remember the syntax so I thought I’d do a short post about it – the flag is in Moq mock object, and is called CallBase, but it does require you to rework your tests a little bit.

A Simple Example

This example is pretty similar to the situation I encountered yesterday, with all the noise taken out.

Lets say I have a base class called ViewModelBase, with a method that does some complex validation:

And a derived type with a method Save like this:

When I’m testing the method “Save”, I probably don’t want to have to test everything inside of “IsValid” – it may even be code from a 3rd party which I definitely don’t want to test. This is where I can use CallBase to my advantage.

Mocking Out Base Class Methods With Moq

The key to using CallBase in this way is to actually mock out the class your are testing, set CallBase to be true on the mock, and then stub out the call to the base class method – but an example says this better:

So what’s happening?

Well we’re creating a mocked version of our target class, but setting the call base property to true – this instructs moq to execute any calls made on the mock, on the actual object itself – i.e. if we call “Save” on the mocked object, our save method will get called.

Next we stub out the call to IsValid – in this case moq will call our stubbed out version of IsValid, rather than the base class implementation.

Then we call our save method on the target object and do our assertions and verifications.


One thing to note though is that this will only work for virtual or abstract base class methods, and that if you have constructor arguments on your target class you will need to pass those arguments to Moq – but thats for another day.


The Essential App Marketing Kit
Subscribe To My Newsletter To Get an Entire Chapter From The Book for FREE
Never display this again
15 Flares Twitter 2 Facebook 0 StumbleUpon 12 Google+ 1 LinkedIn 0 15 Flares ×