Fluent NHibernate, auto mappings, ASP.NET MVC 3, Castle Windsor, and NUnit… and Moq

I’m going for a record: internet’s longest blog post title. FNHAMASPDNMVC3CWNUM is the official acronym of this post.

This is the fourth article in a series on using Fluent NHibernate with auto mappings. This time, I will cover unit testing with NUnit and Moq. If you haven’t already, you might want to catch up:

  1. How to use Fluent NHibernate with auto mappings
  2. Fluent NHibernate, auto mappings and ASP.NET MVC 3
  3. Fluent NHibernate, auto mappings, ASP.NET MVC 3, and Castle Windsor

You may be asking yourself, “What is unit testing and why would I want to do it?” If that’s the case, then you should read my previous article: What is unit testing? Dependency injection?

Here’s what the completed project will look like:

If you don’t see the solution at the top of the Solution Explorer, go to the Tools menu > Options. In the Options window, ensure “Show all settings” is checked, then go to Projects and Solutions on the left and check “Always show solution” on the right:

This time, you don’t need to create a new ASP.NET MVC 3 web application. Instead, open the solution from last time, right click on the solution at the top of the Solution Explorer and choose Add > New Project…:

Choose Visual C# Class Library as the project template and name it CastleFluentNHibernateMvc3.Tests. Once the project has been added to the solution, delete the Class1 class. Next, right click on the Tests project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for NUnit and install it. Also, search for and install Moq.

Once the packages have been downloaded and installed, add a folder to the Tests project named Controllers, then add a class to the Controllers folder named HomeControllerTest. Make this class public and prepend it with the TestFixture attribute, like so:

[TestFixture]
public class HomeControllerTest { }

Finally, we’re ready to write some tests!

Remember, a unit test typically covers a single unit of code. In the case of a MVC application, that means that each action and method deserves its own unit test. Depending on the complexity, some actions and methods deserve several unit tests. Because our application is so simple, however, our unit tests will be relatively simple as well. As you can tell from the previous step, we will be writing unit tests for the actions in our home controller, starting with the Index action. For convenience, here is the code:

public ActionResult Index()
{
    storeRepository.BeginTransaction();

    var stores = storeRepository.GetAll();

    if ( stores == null || !stores.Any() )
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
    
    try
    {
        storeRepository.Commit();

        return View( stores.ToList() );
    }
    catch
    {
        storeRepository.Rollback();

        return View( "Error" );
    }
}

We want to make sure that every time the Index action is called the store repository returns a list of stores and the action returns a view. Testing that the action returns a view is simple enough, so at first we might try something like this:

[Test]
public void Index()
{
    // Arrange
    var controller = new HomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

The first thing you’ll notice is that the Tests project requires a reference to CastleFluentNHibernateMvc3, as well as System.Web.Mvc. Once you’ve added these references, Visual Studio will display this compilation error:

'CastleFluentNHibernateMvc3.Controllers.HomeController' does not contain a constructor that takes 0 arguments

The reason we get this error is because we modified the home controller constructor last time to use dependency injection. We did this because we don’t want to use our real repository in our unit tests. Instead, we want to use a fake (or mock) repository. This is where Moq comes in handy, although it does require a little setup before we can use it. First, we need a field to store our fake repository in the HomeControllerTest class, which we need to reset after each test execution:

[TestFixture]
public class HomeControllerTest
{
    private Mock<IRepository<Store>> storeRepositoryMock;

    [SetUp]
    public void Init()
    {
        storeRepositoryMock = new Mock<IRepository<Store>>();
    }

    // ...
}

Now, we can pass this value to the home controller constructor in our unit test, exposing its mocked instance with Moq’s Object property:

[Test]
public void Index()
{
    // Arrange
    var controller = new HomeController( storeRepositoryMock.Object );

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

Eventually, we may end up with lots of injected dependencies in our home controller constructor, so I like to extract the constructor call to a separate method:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
}

private HomeController GetHomeController()
{
    return new HomeController( storeRepositoryMock.Object );
}

At this point, if we try running our application, we will get a nasty error. We can’t run a class library directly. There are two options for running NUnit tests:

  1. Download NUnit and run it in the console or run the GUI tool. After compiling the Tests project, load the .dll file (located in the project’s bin/Debug folder) in NUnit and run the test.
  2. Download the Visual NUnit extension for Visual Studio. Go to View > Other Windows > Visual NUnit. After compiling the Tests project, select it in Visual NUnit and run the test.

Whichever option you choose, our test should pass with flying colors! Unfortunately, there’s a problem. We’ve made sure our action returns a view, but the view it’s returning is actually the Error view. We can verify this by debugging our test. In Visual Studio, go to Debug > Attach to process… find nunit-agent.exe (if you chose option one above) or VisualNUnitRunner.exe (if you chose option two) in the list of processes and click the Attach button.

Now, we can put a breakpoint in our test and take a closer look at our result. Sure enough, the ViewName is “Error”:

We could have caught this sooner by testing that the view is getting the right model. In this case, our view should be getting a list of stores as its model. We would test for that as follows:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );

    var view = (ViewResult)result;

    Assert.IsInstanceOf<List<Store>>( view.Model );
}

If we run our test again, it should fail. NUnit will display the following error:

CastleFluentNHibernateMvc3.Tests.Controllers.HomeControllerTest.Index:
  Expected: instance of <System.Collections.Generic.List`1[CastleFluentNHibernateMvc3.Models.Store]>
  But was:  null

Let’s put a breakpoint in our home controller this time and find out what’s going on. Doing this, we can see that our store repository is not returning any stores. And why should it? Remember, it’s a fake repository! We have to tell our fake repository what to do when it’s queried for a list of stores. But before we do that, make a copy of the Index test and rename it to Index_NoStoresFound. With a little modification, this test can still be useful:

[Test]
public void Index_NoStoresFound()
{
    // Arrange
    var controller = GetHomeController();

    // Act
    var result = controller.Index();

    // Assert
    Assert.IsInstanceOf<ViewResult>( result );
    
    var view = (ViewResult)result;

    Assert.AreEqual( "Error", view.ViewName );
}

Keeping this test will ensure that the Index action always returns the Error view when our store repository doesn’t return any stores. If this test ever fails (for instance, because the Index action returns the Index view), then something is wrong with our error handling.

Now, let’s fix our Index test. We can use Moq’s Setup method to tell Moq what to return when we ask it for a list of stores:

[Test]
public void Index()
{
    // Arrange
    var controller = GetHomeController();

    var stores = new List<Store>
        {
            new Store()
        };

    storeRepositoryMock.Setup( s => s.GetAll() )
        .Returns( stores.AsQueryable() )
        .Verifiable();

    // Act
    var result = controller.Index();

    // Assert
    storeRepositoryMock.Verify();

    Assert.IsInstanceOf<ViewResult>( result );

    var view = (ViewResult)result;

    Assert.IsInstanceOf<List<Store>>( view.Model );
}

Notice that we can return any list of stores we want, so long as we convert it to an IQueryable because that’s what Moq expects to get back from the GetAll method of our store repository.

That concludes my series on using Fluent NHibernate with auto mappings. As always, let me know if you have any questions or comments. Good luck!

Advertisements

2 thoughts on “Fluent NHibernate, auto mappings, ASP.NET MVC 3, Castle Windsor, and NUnit… and Moq

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