0. Why spend time writing unit tests?

Why should you spend time writing unit tests? Can't I just have the QA team manually test the application and then deploy it directly to production? What's the problem with that?

  1. Saving Money

    You read that right: writing unit tests helps your company save money. Without unit tests, you cannot be certain that each code change you make will allow the application's existing functionality to continue working correctly. Even if you perform manual testing, you still cannot cover every possible scenario, which may lead to customers discovering bugs after the software is delivered. Therefore, unit tests actually help the company save a significant amount of money. The savings will far exceed the cost of the engineer's time spent writing these tests.

  2. Unit Tests Serve as Documentation

    Unit test code can be read as documentation. By simply reading the names of the test methods, you can understand what the method under test does, allowing everyone on the team—even new members who have just joined—to understand what the application does.

  3. Facilitating Application Refactoring

    If you need to refactor the application in the future, unit tests that cover every business workflow will help you identify if you have forgotten to implement any specific requirements during the refactoring process.

  4. Encouraging Programmers to Write Better Code

    Because you need to write better code to accommodate better unit tests, it is like learning to "fight with both hands." Unit tests enable you to write better code, and better code makes it easier for you to write unit tests. This leads to a significant improvement in your coding skills and the overall code quality of the project.

The sample code in this article does not use the recently controversial Moq library, but instead uses NSubstitute.

This article follows up on the previous post: Discussing the Importance of Unit Testing via the Moq Controversy: https://cat.aiursoft.cn/post/2023/8/10/importance-of-unit-testing-with-moq. However, if you only want to learn how to write unit tests, there is no need to read the previous article.

A quick advertisement: 😁 I am currently looking for new job opportunities, preferably with a good work-life balance, based in Qingdao. Remote work opportunities are also welcome. If you are interested, please contact me via email: [email protected]. Thank you!

Below, we will try to learn unit testing through practical examples.

The sample code for this article has been uploaded to GitHub: https://github.com/Kit086/kit.demos/tree/main/UnitTesting

1. Code Under Test

I have prepared an example for testing. It is a simple book management system named BookManager, which includes a Book class, an IBookRepository interface, a BookService class, and several methods. You do not need to examine this code in detail; it is standard business logic code.

Book class:

public sealed class Book
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public string Author { get; set; } = string.Empty;
    public DateTime PublishedDate { get; set; }
    public List<string> Genres { get; set; } = new();

    public Book(int id, string title, string author, DateTime publishedDate, List<string> genres)
    {
        Id = id;
        Title = title;
        Author = author;
        PublishedDate = publishedDate;
        Genres = genres;
    }
}

IBookRepository interface:

public interface IBookRepository
{
    IReadOnlyCollection<Book> GetAllBooks();

    IReadOnlyCollection<Book> GetBooksByAuthor(string author);

    IReadOnlyCollection<Book> GetBooksByPublishedYearRange(int startYear, int endYear);

    Book? GetBookById(int id);

    void AddBook(Book book);

    void UpdateBook(Book book);

    void DeleteBook(int id);
}

BookService class:

public sealed class BookService
{
    private readonly IBookRepository _bookRepository;

    public BookService(IBookRepository bookRepository)
    {
        _bookRepository = bookRepository;
    }

    public IReadOnlyCollection<Book> GetBooksByAuthor(string author)
    {
        if (string.IsNullOrEmpty(author))
        {
            throw new ArgumentException("Author name cannot be null or empty");
        }

        return _bookRepository.GetBooksByAuthor(author);
    }

    public IReadOnlyCollection<Book> GetBooksByPublishedYearRange(int startYear, int endYear)
    {
        if (startYear < 0 || endYear < 0)
        {
            throw new ArgumentException("Year cannot be negative");
        }

        if (startYear > endYear)
        {
            throw new ArgumentException("Start year cannot be greater than end year");
        }

        return _bookRepository.GetBooksByPublishedYearRange(startYear, endYear);
    }
}

We are testing these two methods of the BookService class.

2. How to Build a Test Project

Unit testing is a method for verifying the correctness of code functionality. It can be written and executed using specific frameworks and tools. In this example, we use the three libraries xUnit, NSubstitiue, and FluentAssertions to perform unit testing.

xUnit is a popular .NET unit testing framework that provides features and conventions for writing and organizing test cases. NSubstitiue is a lightweight mocking framework (Mock) that can be used to create and configure mock objects, allowing them to replace real dependencies in tests. FluentAssertions is an assertion library used to verify whether test results meet expectations; it provides assertion methods that are easy to read and express.

When you create a new project in Visual Studio or another IDE, you should see the xUnit template project. Alternatively, you can use the dotnet CLI command: dotnet new xunit -o .\BookManager.Tests.Unit\.

Then, you can install NSubstitiue and FluentAssertions using the NuGet package manager in your IDE, or use the following two dotnet CLI commands:

cd .\BookManager.Tests.Unit\
dotnet add package nsubstitute
dotnet add package fluentassertions

Don't forget to add a project reference from the xUnit project to the BookManager project: dotnet add reference ..\BookManager\.

To write unit tests for BookService, we need to follow the steps below:

  1. Create a new project named BookManager.Tests.Unit, which signifies the unit tests for the BookManager project. This unit test project references the three NuGet libraries xUnit, NSubstitiue, and FluentAssertions, as well as the BookManager project.
  2. Create a BookServiceTests class, and mark each test method with the [Fact] attribute or the [Theory] attribute. We will discuss the difference between these two attributes when we introduce the code later.
  3. In this test class, create an instance of BookService named _sut, which stands for system under test, and assign it in the class constructor. When creating the instance, pass in a mock object of IBookRepository as a parameter, built using NSubstitute. This avoids calling the real BookRepository, thereby preventing any impact on the database, and also eliminates the need to configure database connection strings and other such settings in the unit test project.
  4. Use NSubstitiue to configure the behavior of the mock object, such as returning preset data or throwing exceptions.
  5. Call methods of BookService, and use FluentAssertions to verify that the return values or exceptions meet the expected criteria.
  6. Run all the tests and check whether they pass.

Step 1, creating the project and adding references, is straightforward, so I will not go into detail here. Let's proceed directly to Step 2.

3. Basic Configuration of the BookServiceTests Test Class

public class BookServiceTests
{
    private readonly IBookRepository _bookRepository = Substitute.For<IBookRepository>(); // 为 IBookRepository 接口创建一个模拟对象

    private readonly BookService _sut; // System Under Test 被测试的系统

    private readonly List<Book> _books = new() // 创建一个用于测试的书籍列表
        {
            new Book(1, "The Lord of the Rings", "J.R.R. Tolkien", new DateTime(1954, 7, 29), new List<string>() { "Fantasy", "Adventure" }),
            new Book(2, "The Hobbit", "J.R.R. Tolkien", new DateTime(1937, 9, 21), new List<string>() { "Fantasy", "Children" }),
            new Book(3, "Harry Potter and the Philosopher's Stone", "J.K. Rowling", new DateTime(1997, 6, 26), new List<string>() { "Fantasy", "Young Adult" }),
            new Book(4, "Nineteen Eighty-Four", "George Orwell", new DateTime(1949, 6, 8), new List<string>() { "Dystopian", "Political" })
        };

    public BookServiceTests()
    {
        _sut = new(_bookRepository);
    }
}

This code completes the basic setup of the BookServiceTests test class for steps 2 and 3:

  • We use NSubstitute to create a mock _bookRepository;
  • We instantiate the BookService object _sut that is under test;
  • We pass _bookRepository to _sut as a constructor argument in the test class's constructor;
  • We prepare a list of books as test data.

I have added comments to each line of code in the examples below. Please read them.

Note that our example does not contain much business logic; it only performs some parameter validation. It may not be the best example, but it demonstrates a relatively complete approach to writing unit tests. The mindset for writing unit tests is something you need to continuously develop through practice.

4. Writing Test Methods

[Fact]

First, we write the first test method:

[Fact]
public void GetBooksByAuthor_WithValidAuthorName_ReturnsMatchingBooks()
{
    // Arrange
    var author = "J.R.R. Tolkien"; // 为测试定义作者名 author
    _bookRepository.GetBooksByAuthor(author).Returns(_books.Where(b => b.Author == author).ToList()); // 当调用 _bookRepository.GetBooksByAuthor 且传入参数为 author 时配置模拟对象返回预定义好的书籍列表 _books 中作者为 author 的书籍
    // Act
    var result = _sut.GetBooksByAuthor(author); // 调用参数为 author 的 GetBooksByAuthor 方法,并将返回值赋值给 result 变量
    // Assert
    result.Should().NotBeNull(); // 断言 result 不为 null
    result.Should().HaveCount(2); // 断言 result 包含两本书
    result.Should().OnlyContain(b => b.Author == author); // 断言 result 中的书籍作者都是 author
}

This method is named: GetBooksByAuthor_WithValidAuthorName_ReturnsMatchingBooks. The first part indicates that it tests the GetBooksByAuthor method, the second part indicates that it will input a valid Author Name, and the third part indicates that it will return matching Books.

How about that? Doesn't looking at the test method's name tell you the business function of the method being tested? You might not feel a strong impact from this simple example alone, but it is useful in real-world projects.

This method is marked with [Fact], indicating that it is a test method.

This method is divided into 3 parts: Arrange, Act, and Assert. In other words, arrangement, execution, and assertion. As the names suggest, arrangement involves preparing some test data and setting up mock return values, execution involves executing the method under test on _sut, and assertion involves determining correctness based on the results obtained from the executed method, thereby deciding whether the test passes or fails. I have written the details in the code comments, please read them carefully.

This is where the functionality of NSubstitute comes into play. We use the line of code _bookRepository.GetBooksByAuthor(author).Returns(_books.Where(b => b.Author == author).ToList()); to configure the mock object to return a predefined list of books from _books where the author is author, when _bookRepository.GetBooksByAuthor is called with the parameter author.

Then, we use:

result.Should().NotBeNull(); // 断言 result 不为 null
result.Should().HaveCount(2); // 断言 result 包含两本书
result.Should().OnlyContain(b => b.Author == author); // 断言 result 的书籍作者都是 author

These three lines of code are used to assert the test results. The test will fail if the returned result is null, does not contain both books, or if the Author property of any included book is not equal to the value of the author variable.

[Theory]

Let's take a look at the second testing method:

[Theory]
[InlineData(null)]
[InlineData("")]
public void GetBooksByAuthor_WithNullOrEmptyAuthorName_ThrowsArgumentException(string author)
{
    // Act and Assert
    _sut.Invoking(bs => bs.GetBooksByAuthor(author)) // 用 null 或空字符串为参数调用 GetBooksByAuthor 方法
        .Should().Throw<ArgumentException>() // 验证是否抛出 ArgumentException 异常
        .WithMessage("Author name cannot be null or empty"); // 验证异常消息是否正确
}

Although this test also targets the GetBooksByAuthor method, there is a slight difference. It verifies whether the appropriate exception is thrown when the author parameter is passed as null or "", and whether the corresponding exception message is correct. It uses [Theory], indicating that this method will accept multiple sets of input. It then uses two [InlineData] attributes. This test method will be run twice: once with the author parameter set to null, and once with it set to "". Simple, right?

When null or "" is passed, an ArgumentException should be thrown, with the exception message Author name cannot be null or empty. This test doesn't have an explicit Arrange step, or rather, the Arrange is handled in the common setup. Also, in our approach, the Act and Assert steps are combined.

With this test in place, we no longer need to worry about forgetting to handle cases where the author parameter is null or an empty string; it will automatically catch those issues for you!

Other Examples

The following is the unit test code for another method of BookService, GetBooksByPublishedYearRange.

[Fact]
public void GetBooksByPublishedYearRange_WithValidYearRange_ReturnsMatchingBooks()
{
    // Arrange
    var startYear = 1950; // 为测试定义起始年份
    var endYear = 2000; // 为测试定义结束年份
    _bookRepository.GetBooksByPublishedYearRange(startYear, endYear).Returns(_books.Where(b => b.PublishedDate.Year >= startYear && b.PublishedDate.Year <= endYear).ToList()); // 当调用 _bookRepository.GetBooksByPublishedYearRange 且传入参数为 startYear 和 endYear 时配置模拟对象返回预定义好的书籍列表 _books 中出版年份在范围内的书籍
    // Act
    var result = _sut.GetBooksByPublishedYearRange(startYear, endYear); // 调用带有年份范围的 GetBooksByPublishedYearRange 方法
    // Assert
    result.Should().NotBeNull(); // 验证结果不为 null
    result.Should().HaveCount(2); // 验证结果有两本书
    result.Should().OnlyContain(b => b.PublishedDate.Year >= startYear && b.PublishedDate.Year <= endYear); /// 验证结果只包含出版年份在范围内的书籍
}

[Theory]
[InlineData(-1, 2000)]
[InlineData(-100, -50)]
public void GetBooksByPublishedYearRange_WithNegativeStartYear_ThrowsArgumentException(int startYear, int endYear)
{
    // Act and Assert
    _sut.Invoking(bs => bs.GetBooksByPublishedYearRange(startYear, endYear)) // 用负起始年份调用 GetBooksByPublishedYearRange 方法
        .Should().Throw<ArgumentException>() // 验证是否抛出 ArgumentException 异常
        .WithMessage("Year cannot be negative"); // 验证异常消息是否正确
}

[Theory]
[InlineData(1950, -1)]
[InlineData(-50, -100)]
public void GetBooksByPublishedYearRange_WithNegativeEndYear_ThrowsArgumentException(int startYear, int endYear)
{
    // Act and Assert
    _sut.Invoking(bs => bs.GetBooksByPublishedYearRange(startYear, endYear)) // 用负结束年份调用 GetBooksByPublishedYearRange 方法
        .Should().Throw<ArgumentException>() // 验证是否抛出 ArgumentException 异常
        .WithMessage("Year cannot be negative"); // 验证异常消息是否正确
}

[Theory]
[InlineData(2000, 1950)]
[InlineData(2023, 2022)]
public void GetBooksByPublishedYearRange_WithStartYearGreaterThanEndYear_ThrowsArgumentException(int startYear, int endYear)
{
    // Act and Assert
    _sut.Invoking(bs => bs.GetBooksByPublishedYearRange(startYear, endYear)) // 用起始年份大于结束年份调用 GetBooksByPublishedYearRange 方法
        .Should().Throw<ArgumentException>() // 验证是否抛出 ArgumentException 异常
        .WithMessage("Start year cannot be greater than end year"); // 验证异常消息是否正确
}

[Theory]
[InlineData(1900, 1920)]
[InlineData(2020, 2030)]
public void GetBooksByPublishedYearRange_WithNoMatchingBooks_ReturnsEmptyList(int startYear, int endYear)
{
    // Arrange
    _bookRepository.GetBooksByPublishedYearRange(Arg.Any<int>(), Arg.Any<int>()).Returns(Enumerable.Empty<Book>().ToList()); // 当调用 _bookRepository.GetAllBooks 且传入任意 int 类型参数时配置模拟对象返回预定义的书籍列表 _books
    // Act
    var result = _sut.GetBooksByPublishedYearRange(startYear, endYear); // 调用年份范围不匹配任何书籍的 GetBooksByPublishedYearRange 方法
    // Assert
    result.Should().NotBeNull(); // 验证结果不为 null
    result.Should().BeEmpty(); // 验证结果为空
}

If you understood my previous explanation and these notes, then there is only one thing I need to mention here. NSubstitute allows us to use an argument like Arg.Any<T>() to represent "any data of type T".

5. Run Unit Tests

In addition to running directly in your IDE, you can also run the dotnet test command to execute unit tests:

~\Documents\GitHub\kit.demos\UnitTesting git:main ❯❯❯ dotnet test
  Determining projects to restore...
  Restored C:\Users\kit\Documents\GitHub\kit.demos\UnitTesting\BookManager\BookManager.csproj (in 536 ms).
  Restored C:\Users\kit\Documents\GitHub\kit.demos\UnitTesting\BookManager.Tests.Unit\BookManager.Tests.Unit.csproj (in 602 ms).

.....

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.

Passed!  - Failed:     0, Passed:    12, Skipped:     0, Total:    12, Duration: 86 ms - BookManager.Tests.Unit.dll (net7.0)

You can see that 12 tests were run, and all of them passed.

If you want to run a specific test method individually or debug a test method, please follow the prompts in your IDE. Typically, there is a green triangle button to the left of the line containing the method signature. Alternatively, you can right-click it and select run test or debug test.

However, running it in the IDE provides a more intuitive view of the test results:

Figure 1 - Unit Test Execution Results
Figure 1 - Unit Test Execution Results

There are also features such as generating test report files, but these are not part of the introductory content, so this tutorial does not cover them.

6. Summary

Since this is just a 5-minute introductory tutorial, I won't go into further detail. For the rest, you can simply refer to the official documentation of these libraries to find what you need. I have already covered the core concepts of writing unit tests.

xUnit also offers some advanced features that are not commonly used in unit testing but are very useful for integration testing. If the opportunity arises later, I may consider writing an introductory guide to integration testing.

In my next article, I plan to discuss how to use unit tests to refactor a piece of legacy, poorly written code, demonstrating the practical value of unit testing.

Finally, a small advertisement: 😁 I am currently looking for new job opportunities. Ideally, I’m seeking a role with a good work-life balance, based in Qingdao. Remote work opportunities would also be welcome. If you’re interested, please contact me via email at [email protected]. Thank you!