Search Sreeni's Insights

Filter by content type
crafting January 12, 2016 7 min read

Unit Test Best Practices - FIRST properties

FIRST properties explained through fast, independent, repeatable, self-validating and timely unit tests, with practical guidance for keeping a test suite healthy.

Share:

Unit Test Best Practices - FIRST properties

Almost all teams agree that unit tests are important, but very few teams are happy with the unit tests they have. Some tests are taking minutes to run, some tests are failing randomly on the build server and some tests are passing even when the code is broken. When this happens, developers start ignoring the failed tests and the whole test suite becomes a noise instead of a safety net. As a result of this, bugs are reaching QA and sometimes our customers, and we are back to reactive firefighting.

Last year, we discussed how to write unit tests with NUnit and Moq using the AAA (Arrange, Act, Assert) pattern, which provides a good starting point for beginners. In this article, we are going to see what makes a unit test a good unit test, using the FIRST properties, and the best practices we follow in our team to keep the tests healthy.

TL;DR Summary

  • A good unit test is Fast, Independent, Repeatable, Self-validating and Timely (FIRST).
  • A unit test must not use database, file system, network or system clock, otherwise it breaks first three properties from FIRST.
  • One test should verify one behaviour and the test name should explain that behaviour.
  • A test must fail for one reason only, so the failure message tells us what is broken.
  • Flaky tests are worse than no tests, fix them or delete them.
  • Tests are production code too, apply the same clean code rules to them.

Challenges

Slow test suite

When the test suite takes 10 or 15 minutes to run, developers stop running it before every check-in. They push the code and wait for the build server to tell them. The feedback loop becomes longer and the cost of fixing a bug is going up with every minute it lives.

Flaky tests

A flaky test passes sometimes and fails sometimes, without any change in the code. Normally, it is depending on the order of tests, shared static state, current date or an external service. After few false alarms, nobody trusts the red build anymore, and the real failures are also ignored.

Tests that don’t test

Sometimes, a test has no assertion at all, or it only checks that “no exception is thrown”. It increases the code coverage number, but it gives a false confidence. The code coverage report is looking good, but the blind spots are still there.

Hard to maintain tests

When one small change in production code breaks 40 tests, developers see the tests as a burden. It is mostly because the tests are coupled to the implementation details instead of the behaviour.

What is FIRST?

FIRST is an acronym for the five properties of a good unit test, Fast, Independent, Repeatable, Self-validating and Timely. It was popularised by Tim Ottinger and Brett Schuchert and also described in the “Clean Code” book by Robert C. Martin.

In simple terms, if a unit test is having all five properties, developers will run it often, trust its result and keep it updated.

The following diagram depicts the FIRST properties of a unit test.

FIRST properties of a unit test
FIRST properties of a unit test

Let us take a closer look at each property.

Fast

A unit test should run in milliseconds. We should be able to run hundreds of tests in few seconds, otherwise developers will not run them before every commit. Anything slow like database calls, HTTP calls, file access and Thread.Sleep must be replaced with a test double.

Example:

// Don't - it waits 5 seconds in every run
[Test]
public void PriceCache_AfterExpiry_ReturnsNull()
{
    var cache = new PriceCache(TimeSpan.FromSeconds(5));
    cache.Add("FUND001", 10.50m);

    Thread.Sleep(6000);

    Assert.That(cache.Get("FUND001"), Is.Null);
}

// Do - control the time through an abstraction
[Test]
public void PriceCache_AfterExpiry_ReturnsNull()
{
    var clock = new FakeClock(new DateTime(2016, 3, 1, 10, 0, 0));
    var cache = new PriceCache(TimeSpan.FromSeconds(5), clock);
    cache.Add("FUND001", 10.50m);

    clock.Advance(TimeSpan.FromSeconds(6));

    Assert.That(cache.Get("FUND001"), Is.Null);
}

Independent

A test must not depend on other tests. We should be able to run any test alone, or all tests in any order, and get the same result. Shared static variables, a shared database record and a test which “prepares data for the next test” are the common reasons for dependent tests.

  • Create the system under test (SUT) inside each test or in [SetUp], not in a static field.
  • Don’t use [Order] attribute to make tests pass.
  • Each test should arrange its own data.

Repeatable

A test should give the same result in any environment, developer machine, build server, at midnight or on 29th February. If the test is reading DateTime.Now, a configuration file, environment variable or a random number, it is not repeatable.

It is the main reason for flaky tests on the build server. Wrap such dependencies behind an interface (IClock, IConfigProvider) and inject it, so the test can control the value.

Self-validating

A test must clearly say pass or fail by itself. Nobody should read a log file or compare an output manually to decide whether the test passed.

  • Every test must have at least one assertion.
  • Don’t write Console.WriteLine and check it with eyes.
  • Assertion messages should explain what was expected, NUnit constraint model (Assert.That(actual, Is.EqualTo(expected))) gives better messages by default.

Timely

Tests should be written at the right time, which is just before or along with the production code. When tests are written weeks later, the code is usually hard to test and the developer has already moved on to the next task. Test Driven Development (TDD) takes this property to the extreme, we will discuss whether it is worth for our team in a separate article.

Why FIRST is important?

In order to get fast feedback, to trust the red and green results and to keep the tests updated along with the code, the tests must follow the FIRST properties. A slow test is not run, a flaky test is not trusted and a test without assertion is not useful. All three end in the same place, bugs are found by QA or by our customers instead of by the developer, and the cost of fixing them is much higher.

Other best practices we follow

Apart from FIRST, find below the quick summary of the unit test best practices which we follow across all teams.

Naming

Use MethodName_StateUnderTest_ExpectedBehaviour format. When a test fails in the build report, the name alone should tell us what is broken.

Example: CalculateUnitPrice_WhenNavIsZero_ThrowsArgumentException

One behaviour per test

A test should verify one behaviour. It is not necessary all tests should have exactly one Assert line, but all assertions in one test must be about the same behaviour. Otherwise, when the first assertion fails, we don’t know about the rest.

Test the behaviour, not the implementation

Test what the method returns or changes, not how it does internally. Don’t verify every private call through a mock, it will break the tests on every refactoring. Refer the upcoming Test Double section in the next article for when to use mocks.

No logic in tests

Don’t use if, for or switch inside a test. If a test has logic, it may need its own test. Use [TestCase] for data driven tests instead.

[TestCase(100, 10, 10)]
[TestCase(250, 50, 5)]
[TestCase(0, 10, 0)]
public void CalculateUnitPrice_ReturnsNavDividedByUnits(decimal nav, decimal units, decimal expected)
{
    var calculator = new UnitPriceCalculator();

    var price = calculator.CalculateUnitPrice(nav, units);

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

Keep the tests clean

Tests are read more than production code when something is broken. Use builders or factory methods to create test data (ex: FundBuilder.AnOpenFund().WithCurrency("EUR").Build()) instead of repeating 20 lines of setup in every test.

Must Do and Don’ts

  • Must Do: Run all unit tests locally before check-in and on every CI build.
  • Must Do: Replace database, network, file system and clock with test doubles.
  • Must Do: Fix or delete a flaky test the same day, don’t mark it [Ignore] and forget.
  • Don’t: share state between tests through static fields.
  • Don’t: write a test without an assertion just to increase the coverage.
  • Be mindful: code coverage is a useful indicator but not a goal. 80% coverage with weak assertions is giving less confidence than 60% coverage with strong assertions.

Note: Tests that talk to a real database or service are still valuable, but they are called as integration tests. Keep them in a separate project and run them in a separate stage, so the unit test suite stays fast.

Wrap up

In this article, we have looked at the common challenges with unit tests, the FIRST properties, Fast, Independent, Repeatable, Self-validating and Timely, and some best practices we follow to keep the tests healthy. I really appreciate that you took the time to read this article and I hope this article provided you some insights into writing better unit tests. In the next article, I will walk you through Test Doubles and the difference between stub, mock and fake.

Related Posts