Search Sreeni's Insights

Filter by content type
crafting March 31, 2015 7 min read

How to write unit tests with NUnit and Moq?

Unit testing with NUnit and Moq explained through FIRST properties, the AAA pattern, test doubles, test cases, exceptions, and verification of interactions.

Share:

How to write unit tests with NUnit and Moq?

Unit testing is one of the significant engineering practices for all software teams. Without unit tests, every refactoring is a risk, every release needs long manual testing and bugs are found by the customers instead of by us. In the previous articles, we discussed SOLID Principles - Part 1, SOLID Principles - Part 2 and Dependency Injection, which make the code testable. In this article, we are going to see how to write unit tests in .NET with NUnit and Moq, following the AAA (Arrange, Act, Assert) pattern.

TL;DR Summary

  • Unit test verifies a small unit of code (a method or class) in isolation.
  • Good unit tests follow FIRST - Fast, Independent, Repeatable, Self-validating, Timely.
  • Use AAA (Arrange, Act, Assert) pattern to keep the tests readable.
  • NUnit is the test framework, Moq is the mocking library.
  • Mock only the dependencies of the SUT (system under test), never the SUT itself.
  • A unit test must not use database, file system or network, otherwise it is an integration test.
  • Name the test so that it tells what is tested, under which condition and the expected result.

Challenges

Manual testing doesn’t scale

When the application is small, the developer can test everything manually before each release. When it grows, the manual regression takes days, and the team starts skipping parts of it. Bugs slip into production and the customer finds them first.

Fear of refactoring

Without tests, no one knows whether the change has broken something else. The developers stop improving the code and the technical debt is growing.

Slow and flaky tests

Some teams write “unit tests” which call the real database or a web service. These tests are slow, they fail randomly when the network is down and they need a specific data in the database. Very soon, nobody runs them and they are ignored in the build.

What is a Unit Test?

A unit test is an automated test which verifies the behaviour of a small unit of code, usually a single method or class, in isolation from its dependencies.

In simple terms, we call one method with known inputs and check whether the output is what we expected, without touching the database, file system or network.

A good unit test follows the upcoming FIRST properties,

  • Fast - runs in milliseconds, so we can run thousands of them in every build.
  • Independent - doesn’t depend on other tests or on the order of execution.
  • Repeatable - gives the same result every time, in any environment.
  • Self-validating - passes or fails automatically, no manual check of output.
  • Timely - written at the same time (or before) the production code.

A unit test must not use data base, file system or network calls, otherwise it breaks the first three properties from FIRST.

What is AAA pattern?

AAA stands for Arrange, Act, Assert. It is a simple way to structure every test into three parts,

  • Arrange - set up the SUT and its dependencies, prepare the input.
  • Act - call the method under test.
  • Assert - verify the result or the interaction.

Keeping these three parts visually separated makes the test easy to read, even for someone who is new to the code.

What is a Test Double?

When the SUT depends on a database repository or a pricing service, we replace that dependency with a test double. It is the same idea as a stunt double in movies. The real actor doesn’t jump from the building, the stunt double does it, and the audience can’t see the difference.

Here are the common types,

  • Stub - returns predefined data. Used to give input to the SUT.
  • Mock - records the calls, so we can verify the SUT called it correctly.
  • Fake - a working but simplified implementation, i.e. an in-memory repository.

Moq can create both stubs and mocks with the same Mock<T> class.

Setting up NUnit and Moq

Steps to Implement:

Follow the following instructions to set up a test project.

  • Add a new Class Library project to your solution, name it as <ProjectName>.Tests. For example, Funds.Core.Tests.

  • Install NUnit, the NUnit test adapter (to run tests inside Visual Studio Test Explorer) and Moq from the Package Manager Console.

    Install-Package NUnit -Version 2.6.4 -ProjectName Funds.Core.Tests
    Install-Package NUnitTestAdapter -ProjectName Funds.Core.Tests
    Install-Package Moq -ProjectName Funds.Core.Tests

    Note: NUnit 3 is currently in beta. The examples in this article are working with NUnit 2.6.4, which is the stable version for now.

  • Add a reference to the project which you want to test.

  • Build the solution and open Test → Windows → Test Explorer.

Writing the first test

Let us take a FundService which calculates the market value of a fund using the latest unit price from a repository.

public interface IUnitPriceRepository
{
    decimal? GetLatestPrice(int fundId);
}

public class FundService
{
    private readonly IUnitPriceRepository _priceRepository;

    public FundService(IUnitPriceRepository priceRepository)
    {
        _priceRepository = priceRepository;
    }

    public decimal CalculateMarketValue(int fundId, decimal units)
    {
        if (units < 0)
            throw new ArgumentOutOfRangeException("units", "Units cannot be negative.");

        var price = _priceRepository.GetLatestPrice(fundId);
        if (price == null)
            throw new InvalidOperationException("No price available for fund " + fundId);

        return units * price.Value;
    }
}

Test with a stub

[TestFixture]
public class FundServiceTests
{
    private Mock<IUnitPriceRepository> _priceRepository;
    private FundService _sut;

    [SetUp]
    public void SetUp()
    {
        _priceRepository = new Mock<IUnitPriceRepository>();
        _sut = new FundService(_priceRepository.Object);
    }

    [Test]
    public void CalculateMarketValue_WhenPriceExists_ReturnsUnitsMultipliedByPrice()
    {
        // Arrange
        _priceRepository.Setup(r => r.GetLatestPrice(42)).Returns(12.5m);

        // Act
        var result = _sut.CalculateMarketValue(42, 100m);

        // Assert
        Assert.That(result, Is.EqualTo(1250m));
    }
}

Setup(...).Returns(...) makes the mock act as a stub. The test doesn’t need any database, it runs in milliseconds.

Test for exceptions

[Test]
public void CalculateMarketValue_WhenNoPrice_ThrowsInvalidOperationException()
{
    // Arrange
    _priceRepository.Setup(r => r.GetLatestPrice(It.IsAny<int>())).Returns((decimal?)null);

    // Act & Assert
    Assert.Throws<InvalidOperationException>(() => _sut.CalculateMarketValue(42, 100m));
}

Data driven tests with TestCase

When the same logic needs to be tested with different inputs, use [TestCase] instead of copying the test.

[TestCase(0, 10, 0)]
[TestCase(100, 10, 1000)]
[TestCase(2.5, 4, 10)]
public void CalculateMarketValue_ReturnsExpectedValue(decimal units, decimal price, decimal expected)
{
    _priceRepository.Setup(r => r.GetLatestPrice(1)).Returns(price);

    var result = _sut.CalculateMarketValue(1, units);

    Assert.That(result, Is.EqualTo(expected));
}

Verify the interaction with a mock

Sometimes the method doesn’t return anything, it calls a dependency. In this case, we verify the call.

[Test]
public void PublishFund_WhenValid_SendsNotificationOnce()
{
    // Arrange
    var notifier = new Mock<INotificationService>();
    var publisher = new FundPublisher(notifier.Object);
    var fund = new Fund { Id = 7, Name = "Global Equity" };

    // Act
    publisher.Publish(fund);

    // Assert
    notifier.Verify(n => n.NotifySubscribers(fund), Times.Once());
}
  • Just to pulse check, run all tests from Test Explorer (Ctrl+R, A). All tests should be green and the total time should be few hundred milliseconds.

Best Practices

  • Naming - Use MethodName_Condition_ExpectedResult pattern (ex: CalculateMarketValue_WhenNoPrice_ThrowsInvalidOperationException). When a test fails in the build, the name should tell what is broken.
  • One logical assert per test - Test one behaviour per test, otherwise when it fails, you don’t know which part is broken.
  • Don’t mock what you don’t own - Wrap the third-party classes in your own interface and mock the interface.
  • Don’t mock the SUT - Only the dependencies are mocked.
  • Avoid logic in tests - No if, loops or try-catch inside tests. Tests should be simple enough that they don’t need their own tests.
  • Keep tests independent - Use [SetUp] to create fresh objects for each test, don’t share state between tests.
  • Don’t over verify - Verifying every call makes the tests fragile, verify only the interactions which are part of the behaviour.

Info: Run the unit tests in every build in your continuous integration. We will discuss continuous integration with Visual Studio Online in an upcoming article.

Wrap up

In this article, we have looked at what is a unit test, the FIRST properties, the AAA pattern, test doubles and how to write tests with NUnit and Moq including stubs, exceptions, test cases and verification. I hope this article provided you some insights into unit testing. In the next article, I will walk you through a code review checklist for .NET teams.

Related Posts