Search Sreeni's Insights

Filter by content type
technical December 18, 2012 12 min read

How to test the application and keep it clean? - Part 12

This article shows how to unit test services, controllers, routes, helpers and the Web API with fakes, write integration tests with a rolled back transaction, and review SOLID in the application.

Share:

How to test the application and keep it clean? - Part 12

An application without the tests works fine on the day we release it, and it slowly becomes the application which nobody dares to change. Every change needs a manual check of all the screens, the checks are skipped when the deadline is near, and the bugs reach the users. In the previous article, we built the create student screen, and we kept all the dependencies as interfaces. Now we are going to take the benefit of that decision. In this article, we are going to see how to write the unit tests for the services and the controllers, the integration tests for the queries with the real database, and how the SOLID principles show up in the complete application.

Student Management System series:

  1. How to structure an ASP.NET MVC application? - Part 1
  2. How does an ASP.NET MVC request work from .NET 4.0 to 4.5? - Part 2
  3. How does routing work, with custom, nested and area routes? - Part 3
  4. How to model the data with Entity Framework and LINQ? - Part 4
  5. How lambda expressions, extension methods, delegates and events reduce the code? - Part 5
  6. How to build CRUD with Razor views and dependency injection? - Part 6
  7. How to remove the repeated code with a base controller, base service and base repository? - Part 7
  8. How to build the views with layouts, partial views and HTML helpers? - Part 8
  9. How to use filters, model binding and validation? - Part 9
  10. How to add registration, login, forgot password, change password, profile and logout? - Part 10
  11. How to build a Web API with ASP.NET MVC 4? - Part 11
  12. How to test the application and keep it clean? - Part 12 (this article)

TL;DR Summary

  • A unit test checks one class alone, with its dependencies replaced by fakes. It is fast and has no database, no web server.
  • An integration test checks that the parts work together with the real thing, like Entity Framework and SQL Server. It is slower, so write fewer of them.
  • Because the controller is a normal class and an action returns an ActionResult, we can test it without a web server.
  • Use a fake or a mock library like Moq for the dependencies, and a TransactionScope to roll back the data of an integration test.
  • Test the behavior and not the implementation, otherwise every refactoring breaks the tests.
  • The principles of the Maintainable Code series are the reason why all of this is possible.

Common Challenges

Tests which need the whole system

If the only way to test an enrollment rule is to start the web site, open the browser and click, nobody will test it often. A test which needs the database, the mail server and the web server fails for the reasons which have nothing to do with the rule.

Slow tests

A test suite which takes half an hour is run once a week, and then it can’t tell us which change broke the code. The tests must be quick, so that we run them at every build.

Tests which break for every change

When the tests know how the code is written (which private method calls which), a refactoring which keeps the behavior still breaks them. The team then stops trusting the tests, or stops refactoring.

Unit tests

A unit test has three steps, the AAA pattern, Arrange (set up the objects), Act (call the method) and Assert (check the result). Find below the test for the search in StudentService. We use NUnit here, but the same works with MSTest or xUnit.

First, a fake repository which keeps the students in a list in the memory,

public class FakeStudentRepository : IStudentRepository
{
    public readonly List<Student> Students = new List<Student>();

    public IQueryable<Student> GetAll() { return Students.AsQueryable(); }
    public Student Find(int id) { return Students.FirstOrDefault(s => s.Id == id); }
    public void Add(Student student) { Students.Add(student); }
    public void Remove(Student student) { Students.Remove(student); }
}

public class FakeLogger : ILogger
{
    public readonly List<string> Lines = new List<string>();
    public int Errors;

    public void Debug(string format, params object[] args) { Lines.Add("DEBUG " + string.Format(format, args)); }
    public void Info(string format, params object[] args) { Lines.Add("INFO " + string.Format(format, args)); }
    public void Warn(string format, params object[] args) { Lines.Add("WARN " + string.Format(format, args)); }
    public void Error(Exception exception, string format, params object[] args) { Errors++; Lines.Add("ERROR " + string.Format(format, args)); }
}

public class FakeUnitOfWork : IUnitOfWork
{
    public int Commits;
    public void Commit() { Commits++; }
}

Then the tests,

[TestFixture]
public class StudentServiceTests
{
    private FakeStudentRepository _repository;
    private FakeUnitOfWork _unitOfWork;
    private StudentService _service;

    [SetUp]
    public void SetUp()
    {
        _repository = new FakeStudentRepository();
        _unitOfWork = new FakeUnitOfWork();
        _service = new StudentService(_repository, _unitOfWork, new FakeLogger());
    }

    [Test]
    public void Search_ReturnsOnlyTheStudentsWithTheLastName()
    {
        _repository.Students.Add(new Student { LastName = "Kumar" });
        _repository.Students.Add(new Student { LastName = "Raj" });

        var result = _service.Search("Kum", 1, 10);

        Assert.AreEqual(1, result.Count);
        Assert.AreEqual("Kumar", result[0].LastName);
    }

    [Test]
    public void Create_SavesTheStudentAndCommitsOnce()
    {
        _service.Create(new Student { LastName = "Kumar" });

        Assert.AreEqual(1, _repository.Students.Count);
        Assert.AreEqual(1, _unitOfWork.Commits);
    }
}

The sample has some more tests, for the paging, the delete and the enrollment, and you can find them in the StudentServiceTests class. The following diagram shows what is involved in this test.

Unit test with a fake vs integration test with a database
Unit test with a fake vs integration test with a database

Find below the result of running the whole unit test project with the NUnit console runner. The tests of the service, the controllers (with the base controller), the routes, the helper, the validation attribute and the Web API controller together run in about one second,

SMS.Tests.HtmlHelperTests.GradeBadge_RendersASpanWithTheGradeClass
SMS.Tests.HtmlHelperTests.GradeBadge_WhenThereIsNoGrade_RendersADash
SMS.Tests.RoutingTests.TheBirthYearConstraint_AcceptsARealisticYear
SMS.Tests.RoutingTests.TheBirthYearConstraint_RejectsAnUnrealisticYear
SMS.Tests.RoutingTests.TheDefaultRoute_MapsTheIdSegment
SMS.Tests.RoutingTests.TheNestedRoute_DoesNotMatchANonNumericDepartment
SMS.Tests.RoutingTests.TheNestedRoute_MapsTheDepartmentAndTheCourse
SMS.Tests.RoutingTests.TheRootUrl_GoesToTheStudentsIndex
SMS.Tests.RoutingTests.TheUrl_IsGeneratedFromTheRouteValues
SMS.Tests.StudentsApiTests.Delete_WhenTheStudentExists_ReturnsNoContent
SMS.Tests.StudentsApiTests.Get_WhenTheStudentDoesNotExist_ReturnsNotFound
SMS.Tests.StudentsApiTests.Post_WhenARuleRejectsTheStudent_ReturnsConflict
SMS.Tests.StudentsApiTests.Post_WhenTheServiceFails_ReturnsServerErrorAndLogsIt
SMS.Tests.StudentsApiTests.Post_WithAnInvalidModel_ReturnsBadRequest
SMS.Tests.StudentsApiTests.Post_WithAValidStudent_ReturnsCreatedWithTheLocation
SMS.Tests.StudentsControllerTests.AnUnexpectedException_IsLoggedAndShowsTheErrorView
SMS.Tests.StudentsControllerTests.Create_WhenModelIsInvalid_ReturnsTheSameViewAndDoesNotSave
SMS.Tests.StudentsControllerTests.Create_WhenModelIsValid_RedirectsToIndex
SMS.Tests.StudentsControllerTests.Create_WhenTheServiceRejectsTheStudent_ShowsTheMessageInTheForm
SMS.Tests.StudentsControllerTests.Details_WhenTheStudentDoesNotExist_ReturnsNotFound
SMS.Tests.StudentServiceTests.Create_SavesTheStudentAndCommitsOnce
SMS.Tests.StudentServiceTests.Create_WithADuplicateEmail_ThrowsABusinessRuleException
SMS.Tests.StudentServiceTests.Delete_RemovesTheStudent
SMS.Tests.StudentServiceTests.Enroll_AddsTheEnrollmentAndRaisesTheEvent
SMS.Tests.StudentServiceTests.Enroll_ForAMissingStudent_IsLoggedAsAWarningAndNotAsAnError
SMS.Tests.StudentServiceTests.Enroll_InTheSameCourseTwice_Throws
SMS.Tests.StudentServiceTests.Execute_LogsTheStartAndTheEndOfAnOperation
SMS.Tests.StudentServiceTests.Search_ReturnsOnlyTheStudentsWithTheLastName
SMS.Tests.StudentServiceTests.Search_ReturnsTheRequestedPage
SMS.Tests.ValidationTests.MinimumAge_RejectsAStudentWhoIsTooYoung
Tests run: 64, Errors: 0, Failures: 0, Inconclusive: 0, Time: 0.97 seconds

There is no database, so the test runs in milliseconds, and it fails only when the logic of the service is wrong. It was possible only because the service depends on the IStudentRepository and not on the SchoolContext (Dependency Inversion Principle). A library like Moq can create such fakes for us in one line, new Mock<IStudentRepository>(), which is useful when you need only one method of a big interface or you want to verify that a call was made. For a simple repository like this, the hand-written fake is easy to read.

Testing a controller

An action returns a description of the result, so we can check it without the web server.

The controller depends on the IStudentService, so we need a fake of it. The fake only counts the calls, which is enough for the tests below,

public class FakeStudentService : IStudentService
{
    public readonly List<Student> Students = new List<Student>();
    public int CreateCalls;
    public Exception CreateException;

    public event EventHandler<StudentEnrolledEventArgs> StudentEnrolled { add { } remove { } }

    public IList<Student> Search(string term, int pageNumber, int pageSize) { return Students; }
    public IList<Student> BornIn(int year) { return new List<Student>(); }
    public int Count() { return 0; }
    public Student Find(int id) { return Students.FirstOrDefault(s => s.Id == id); }
    public int Create(Student student)
    {
        if (CreateException != null) throw CreateException;
        CreateCalls++;
        student.Id = 42;
        return 42;
    }
    public void Update(Student student) { }
    public void Delete(int id) { }
    public void Enroll(int studentId, int courseId) { }
}
[Test]
public void Create_WhenModelIsInvalid_ReturnsTheSameViewAndDoesNotSave()
{
    var service = new FakeStudentService();
    var controller = new StudentsController(service, new FakeCatalogService(), new FakeLogger());
    controller.ModelState.AddModelError("LastName", "Required");

    var result = controller.Create(new StudentFormModel()) as ViewResult;

    Assert.IsNotNull(result);
    Assert.AreEqual(0, service.CreateCalls);
}

[Test]
public void Create_WhenModelIsValid_RedirectsToIndex()
{
    var controller = new StudentsController(new FakeStudentService(), new FakeCatalogService(), new FakeLogger());

    var result = controller.Create(new StudentFormModel { LastName = "Kumar" }) as RedirectToRouteResult;

    Assert.IsNotNull(result);
    Assert.AreEqual("Index", result.RouteValues["action"]);
}

We add the error to the ModelState ourselves, because the model binder doesn’t run in a unit test. That is not a problem, the model binding and the validation are the framework’s job, and we test only our decision. The controller is thin, so there are only few tests for it.

Must Be Aware: Don’t write a unit test which only checks the framework, for example that the [Required] attribute makes the field required. It is already tested by Microsoft. Test our rules, the decisions and the calculations.

Testing the routes

The routes are code, and a mistake in the order or a constraint breaks the whole application, so they deserve the tests. The route table can be matched without a web server, if we give it a fake HttpContext with a request which has the URL. The routing needs only a few members of them,

public class FakeRequest : HttpRequestBase
{
    private readonly string _url;

    public FakeRequest(string url) { _url = url; }

    public override string AppRelativeCurrentExecutionFilePath { get { return _url; } }
    public override string PathInfo { get { return string.Empty; } }
    public override string ApplicationPath { get { return "/"; } }
    public override NameValueCollection ServerVariables { get { return new NameValueCollection(); } }
}

public class FakeResponse : HttpResponseBase
{
    public override string ApplyAppPathModifier(string virtualPath) { return virtualPath; }
}

public class FakeHttpContext : HttpContextBase
{
    private readonly HttpRequestBase _request;
    private readonly HttpResponseBase _response = new FakeResponse();

    public FakeHttpContext(string url) { _request = new FakeRequest(url); }

    public override HttpRequestBase Request { get { return _request; } }
    public override HttpResponseBase Response { get { return _response; } }
}

Each member which is not overridden throws a NotImplementedException, and that is how we found the members which the routing needs (ServerVariables was required for the URL generation). Now the tests use the real RouteConfig,

[TestFixture]
public class RoutingTests
{
    private RouteCollection _routes;

    [SetUp]
    public void SetUp()
    {
        _routes = new RouteCollection();
        RouteConfig.RegisterRoutes(_routes);
    }

    private RouteData Match(string url)
    {
        return _routes.GetRouteData(new FakeHttpContext(url));
    }

    [Test]
    public void TheNestedRoute_MapsTheDepartmentAndTheCourse()
    {
        var data = Match("~/departments/2/courses/3");

        Assert.AreEqual("Courses", data.Values["controller"]);
        Assert.AreEqual("Details", data.Values["action"]);
        Assert.AreEqual("2", data.Values["departmentId"]);
        Assert.AreEqual("3", data.Values["id"]);
    }

    [Test]
    public void TheBirthYearConstraint_RejectsAnUnrealisticYear()
    {
        var data = Match("~/students/born/1800");

        // the constraint fails, so the default route treats born as the action
        Assert.AreEqual("born", data.Values["action"]);
    }

    [Test]
    public void TheUrl_IsGeneratedFromTheRouteValues()
    {
        var context = new RequestContext(new FakeHttpContext("~/"), new RouteData());

        var url = UrlHelper.GenerateUrl(null, "Index", "Courses",
            new RouteValueDictionary(new { departmentId = 2 }), _routes, context, true);

        Assert.AreEqual("/departments/2/courses", url);
    }
}

The first test proves the matching of the nested route, the second one proves the custom constraint (and shows what the default route does with the rejected URL), and the third one proves the generation of the URL in the other direction. If somebody registers the Default route first, these tests fail at once. The area route and the Web API route are not in this RouteConfig, so they are not covered by these tests.

Note: The unit tests of the account features (the password hasher, the lock and the reset token with a fake clock, the controller with a fake authenticator and a signed in user, Part 10), the HTML helper (Part 8), the validation attribute (Part 9), the Web API controller (Part 11) and the base classes (Part 7, the fake logger tests of the service and the controller) are in the same project, and you can find them in the sample code.

Integration tests

The fake repository proves that the service is right, but it can’t prove that the real query works. A LINQ query which runs well on a list in memory can fail with EF, because the provider can’t translate some expression (Part 4). The integration tests use the real SchoolContext and a test database.

[TestFixture]
public class StudentRepositoryTests
{
    private TransactionScope _scope;
    private SchoolContext _context;

    [TestFixtureSetUp]
    public void CreateTheDatabase()
    {
        using (var context = new SchoolContext())
            context.Database.Initialize(false);
    }

    [SetUp]
    public void SetUp()
    {
        _scope = new TransactionScope();
        _context = new SchoolContext();
    }

    [TearDown]
    public void TearDown()
    {
        _context.Dispose();
        _scope.Dispose();   // never completed, so everything is rolled back
    }

    [Test]
    public void GetAll_FindsAStudentByTheLastNamePart()
    {
        _context.Students.Add(new Student { FirstName = "A", LastName = "Zzyzx", Email = "a@example.com", DateOfBirth = new DateTime(1990, 1, 1), CreatedOn = DateTime.UtcNow });
        _context.SaveChanges();
        var repository = new StudentRepository(_context, new NullLogger());

        var found = repository.GetAll().Where(s => s.LastName.StartsWith("Zzy")).ToList();

        Assert.AreEqual(1, found.Count);
    }

    [Test]
    public void Find_LoadsTheEnrollmentsWithTheCourses()
    {
        var repository = new StudentRepository(_context, new NullLogger());
        var id = repository.GetAll().Where(s => s.LastName == "Kumar").Select(s => s.Id).First();

        var student = repository.Find(id);

        Assert.IsTrue(student.Enrollments.Any());
        Assert.IsNotNull(student.Enrollments.First().Course.Title);
    }
}

The TestFixtureSetUp creates and seeds the database once, before the first test, with the initializer of Part 4. We do it outside the TransactionScope, because a database can’t be created inside a transaction. The second test reads the seeded data, so it proves that the Include of the repository really loads the courses. The test project has its own App.config with its own connection string, and the database name is SMS_IntegrationTests.

The TransactionScope is never completed, so when it is disposed, everything which the test wrote is rolled back, and every test starts with the same data. Point the test project to a separate test database, and never to the real one.

The following is the result of the integration tests, the first run takes more time because it creates the database,

Execution Runtime: net-4.0
..
Tests run: 5, Errors: 0, Failures: 0, Inconclusive: 0, Time: 3.2 seconds

Integration tests are slow, because they use the database, so keep the number small. Write them for the things which only the real database can prove, the queries, the mappings, the constraints and the migrations. The business rules belong to the unit tests.

SOLID in the Student Management System

We started this journey with the principles in the Maintainable Code series, and we have used all of them in this application. Find below where each one shows up,

PrincipleWhere we used it
Single ResponsibilityThe controller coordinates, the service has the logic, the repository has the queries, the view model carries the form
Open ClosedThe StudentEnrolled event, a new listener doesn’t change the service
Liskov SubstitutionThe fake repository replaces the EF repository in the tests, without the service noticing
Interface SegregationSmall interfaces like IUnitOfWork and IStudentRepository, and not one big data access interface
Dependency InversionThe Domain defines the interfaces, the Data project implements them, and the container wires them

Because of these, the application follows the Tell Don’t Ask and the Law of Demeter also, the controller tells the service what to do, and it doesn’t walk through the object graph of the student.

Must Consider: The structure of this series is intentionally a little more than a very small application needs, to show the ideas. For a real application, apply the layers and the abstractions where the change and the testing are really expected (YAGNI), and keep the rest simple.

Wrap up

In this article, we have looked at how to write the unit tests for the services and the controllers, the integration tests with a rolled back transaction, and how the SOLID principles are applied in the complete application. I really appreciate that you took the time to read this series. In the next series, I will walk you through the clean code and the refactoring, to improve the existing code safely with the help of these tests.

Related Posts