Quantcast
Channel: Codenutz - all about how to make an app » Moq
Viewing all articles
Browse latest Browse all 3

Unit Testing: Mocking Base Class Methods With Moq

$
0
0

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:

public abstract class ViewModelBase
{
    public virtual bool IsValid()
    {
        //some complex shared stuff here
    }
}

And a derived type with a method Save like this:

public class MyViewModel : ViewModelBase
{
    public void Save()
    {
        if (IsValid())
        {
            //do something here
        }
    }
}

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:

[TestMethod]
public void MyTest()
{
    //arrange
    var mockMyViewModel = new Mock<MyViewModel>(){CallBase = true};
    mockMyViewModel.Setup(x => x.IsValid()).Returns(true);

    //act
    mockMyViewModel.Object.Save();

    //assert
    //do your assertions here
}

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.

Finally

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 post Unit Testing: Mocking Base Class Methods With Moq appeared first on Codenutz - all about how to make an app.


Viewing all articles
Browse latest Browse all 3

Trending Articles