LP on .NET

January 2, 2012

Introduction to Unit Testing with Moq

Filed under: .NET,C# — Larry Parker @ 1:31 pm

If you’ve kept up with my blog over the last year or so, you may have noticed that I discussed certain aspects of unit testing (like writing testable code and unit testing using stubs) but haven’t mentioned much about mocking frameworks.

Mocking frameworks, simply put, allow you to easily simulate behavior of objects and interfaces and are therefore very useful for unit testing.  But before I show an example of mocking, let’s see how we can do something similar by writing our own stubs.

The following example is from the Writing Testable Code post:

public class UserManager {
    public UserManager(IUserPersistence userPersistence, IEmailManager emailManager)
    {
        _userPersistence = userPersistence;
        _emailManager = emailManager;
    }

    private IUserPersistence _userPersistence;
    private IEmailManager _emailManager;

    public Boolean RegisterUser(String lastName, String firstName, String emailAddress)
    {
        try {
            Boolean result = false;

            if (_userPersistence.AddUser(lastName, firstName, emailAddress))
                result = _emailManager.SendUserRegistrationEmail(lastName, firstName,
                    emailAddress);

            return result;
        }
        catch (Exception ex)
        {
            // Log the exception... return false; }
    }
}

public interface IUserPersistence {
    Boolean AddUser(String lastName, String firstName, String emailAddress);
    // Other interface members... }

public interface IEmailManager {
    Boolean SendUserRegistrationEmail(String lastName, String firstName, String emailAddress);
    // Other interface members... }

 

Note that the UserManager constructor takes parameters for the interface references used by RegisterUser.

Now we can write stubs to simulate these interfaces:

public class UserPersistenceStub : IUserPersistence {
    public Boolean AddUser(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

public class EmailManagerStub : IEmailManager {
    public Boolean SendUserRegistrationEmail(String lastName, String firstName,
        String emailAddress)
    {
        return true;
    }
}

 

These stubs don’t do very much, but they allow us to use them in a unit test like this:

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceStub = new UserPersistenceStub();
    var emailManagerStub = new EmailManagerStub();

    UserManager target = new UserManager(userPersistenceStub, emailManagerStub);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

This test calls the RegisterUser method and simply asserts that it returns true.  If you look at the RegisterUser code, the only way that this will happen is if the SendUserRegistrationEmail method that it calls (via the IEmailManager reference) also returns true.

Since we wrote our IEmailManager stub to do this (i.e. the EmailManagerStub class) and also wrote our test to inject it into the UserManager constructor, our test passes.

So we didn’t even need a mocking framework to write a unit test in this example.  We simply wrote some stubs to simulate the interfaces needed by the method being tested.

However, the problem with stubs is that they are tedious to write.  That’s where a mocking framework comes in.  There are many excellent mocking frameworks out there, but I chose Moq after a colleague gave me a quick demo.

Let’s rewrite our unit test to use Moq instead of stubs.  Assuming we’ve installed Moq and added a reference to our unit test project, we first need to do a “using” statement:

using Moq;

 

Now we can rewrite our test like this:

[TestMethod()]
public void RegisterUserTest()
{
 var userPersistenceMock = new Mock<IUserPersistence>(); var emailManagerMock = new Mock<IEmailManager>(); 
    UserManager target = new UserManager(userPersistenceMock.Object, emailManagerMock.Object);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

Instead of creating our own stub classes that implement the injected IUserPersistence and IEmailManager interfaces, we simply use the Mock<T> class and specify the interface we wish to mock.  Then we pass the mocked interfaces into our UserManager constructor with the mocked object’s Object property.

And we’re done.  No stub classes to write.  Wow, that was easy!  🙂

So let’s run our test!

image

Oops.  What happened?

Our test is expecting the RegisterUser method to return true but it didn’t.  As we saw when writing our stubs, the SendUserRegistrationEmail method needs to return true, so that’s what we did for the stub.

But how do we tell Moq to return true for this method?

To do this, we need to set up our mock object like this:

var emailManagerMock = new Mock<IEmailManager>();
emailManagerMock.Setup(o => o.SendUserRegistrationEmail("Smith", "Bert", "bsmith@wherever.com")) .Returns(true);

 

This tells the Moq framework that when IEmailManager.SendUserRegistrationEmail is called with the above parameters that it will return true.  The lambda expression variable (“o” in this case) is typed to the interface being mocked (i.e. IEmailManager).

We also need to do something similar for IUserPersistence so our test can pass.  Here’s the full test:

[TestMethod()]
public void RegisterUserTest()
{
    var userPersistenceMock = new Mock<IUserPersistence>();
    userPersistenceMock.Setup(o => o.AddUser("Smith", "Bert", "bsmith@wherever.com"))
        .Returns(true);

    var emailManagerMock = new Mock<IEmailManager>();
    emailManagerMock.Setup(o => o.SendUserRegistrationEmail("Smith", "Bert", "bsmith@wherever.com"))
        .Returns(true);

    UserManager target = new UserManager(userPersistenceMock.Object, emailManagerMock.Object);
    Boolean actual = target.RegisterUser("Smith", "Bert", "bsmith@wherever.com");
    Assert.IsTrue(actual);
}

 

Now when we run our test it passes! 🙂

image

Much easier with Moq than writing our own stubs.  You can consider stubs a thing of the past.

But our test can be simplified a bit.  We don’t really care about specific parameters passed to our interface methods, so we can use Moq’s “It” class to make our test setups a bit more general:

var userPersistenceMock = new Mock<IUserPersistence>();
userPersistenceMock.Setup(o => o.AddUser(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<String>()))
    .Returns(true);

var emailManagerMock = new Mock<IEmailManager>();
emailManagerMock.Setup(o => o.SendUserRegistrationEmail(It.IsAny<String>(), It.IsAny<String>(), It.IsAny<String>()))
    .Returns(true);

 

This tells Moq that we’re setting up a return value of true for these two methods when any parameters are passed to it.  For our test, this is acceptable.

Well, that was a quick introduction to Moq.  Hopefully I’ve demonstrated that mocking frameworks (like Moq) can be very useful for writing unit tests since they make it easy to simulate the behavior of the objects and interfaces used by the code being tested.

Once I grasped the power of Moq, I never looked back.

Happy mocking!

Advertisements

8 Comments »

  1. It’s a simple and well explained article… Great work!

    Comment by Ravi Ganesan — April 26, 2012 @ 9:19 am | Reply

  2. Good article. I always had my head banging whenever i was given unit testing in my project. Now i can do it so expertly. Thanks a lot.

    Comment by Deepika (@daku_dt) — May 30, 2012 @ 2:51 am | Reply

  3. Very good article!!. Thanks.

    Comment by swapna — August 30, 2012 @ 7:15 pm | Reply

  4. Very simple example but it assumes that all interfaces used by the target class are passed into the constructor. What if the target class/method is creating its own dependanciew, as is usually the case.

    Comment by steve — February 20, 2013 @ 11:27 pm | Reply

  5. @Steve, if I’m understanding your question correctly, you’re asking what if the UserManager class creates its own concrete classes? If that’s the case, it’s difficult to test the code.

    I wrote about writing testable code here:

    https://larryparkerdotnet.wordpress.com/2011/08/14/writing-testable-code/

    Comment by Larry Parker — February 25, 2013 @ 5:11 pm | Reply

  6. […] blogged a lot over the past few years about writing testable code, as well as using stubs and mocking frameworks in unit tests to test all that testable […]

    Pingback by Dependency Injection – A Compromise | LP on .NET — April 3, 2013 @ 9:38 pm | Reply

  7. Nice Article, Thanks….

    Comment by abhishek — April 26, 2013 @ 1:00 am | Reply

  8. […] services, including a custom event aggregator mock.  The other services are mocked using Moq which we use at work for all of our mocking needs.  It works well, is easy to use and I can say […]

    Pingback by Unit Testing ViewModels In Prism Modules | John Gilliland — October 28, 2013 @ 7:15 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: