Skip to content
Back to log

Writing unit tests in test-driven development

Chainabit's Chao · · 8 min read

In short

Explore how to structure unit tests, handle dependencies, and understand the limits of different testing levels, drawing on Microsoft Learn and Martin Fowler.

In test-driven development, it’s important to make clear what a test checks and what result it expects. Microsoft Learn uses unit tests to show how code should behave given a particular input and to verify that behavior. A well-named test can convey the expected result without requiring you to read the method’s implementation.

The scope of a unit test

According to Microsoft Learn, unit tests help you determine whether a change to an application has broken existing functionality. Bugs introduced by a change are called regressions. You can rerun the test suite after every build or after changing a line of code.

A functional test involves opening the application and following a series of steps to verify the expected behavior. You can repeat those steps after every change. In a unit test, the test runner determines whether the test passes automatically.

Microsoft Learn describes a good unit test as fast, isolated, repeatable, and self-checking. A repeatable test gives the same result when nothing changes between runs. An isolated test runs independently of external dependencies such as the file system or a database.

Writing a test should take a reasonable amount of time relative to writing the code it covers. Microsoft Learn suggests considering a design that makes the code easier to test if writing the tests takes considerably longer than writing the code itself. This criterion takes into account both the test result and the time it takes to write the test.

Naming tests for the behavior they verify

Microsoft Learn recommends including three parts in a test name. These are the name of the method under test, the scenario being tested, and the expected behavior in that scenario. The name tells you what the test verifies and under what conditions. If the test fails, it also helps you identify which scenario fell short of expectations.

In Microsoft Learn’s StringCalculator example, Add_SingleNumber_ReturnsSameNumber replaces the name Test_Single. The longer name identifies the Add method, the single-number scenario, and the expectation that the same number will be returned. The test compares the result of Add("0") with zero.

The same approach applies to empty input. The name Add_EmptyString_ReturnsZero tells you that an empty string should produce a result of zero. The test name captures both the input and the result to verify.

The Arrange, Act, Assert pattern

Microsoft Learn describes the Arrange, Act, Assert pattern for writing unit tests. In Arrange, you create and configure the objects you need. In Act, you perform an operation on the object. In Assert, you verify that the result matches your expectation.

These separate steps make it clear which dependencies the code uses, how the call is made, and what result the test checks. Microsoft Learn notes that combining the steps can make the test shorter and emphasizes readability as the goal. Keeping the steps separate also helps prevent assertions from getting mixed in with the Act code.

In the empty string example, Arrange creates a StringCalculator. Act stores the result of Add("") in the actual variable. Assert checks that actual is zero. The pattern shows object creation, the method call, and result verification as separate operations.

Microsoft Learn recommends one Act step per test. You can write separate tests for separate actions or use a parameterized test. A single Act step makes it easier to see which operation failed and which scenario the test covers.

When a test includes multiple Act steps, each one needs its own verification. Microsoft Learn notes that once an Assert step fails, subsequent checks may never run. The test result can therefore leave it unclear whether other functionality is working.

Keeping inputs and test logic simple

According to Microsoft Learn, a unit test should use the simplest input that can verify the behavior under test. Unnecessary model properties or nonzero values where zero would suffice can distract from the behavior the test is meant to verify.

In the example that checks what Add returns for a single number, Microsoft Learn uses "0" as the input in place of a nonzero number. The test still verifies the value returned for a single number. The simple input keeps the focus on the behavior under test and gives the reader fewer implementation details to think about.

Hard-coded string values with no explanation can also make tests hard to read. Microsoft Learn calls these magic strings. To understand why an unusual value appears in a test, the reader may have to dig into implementation details. Microsoft Learn recommends giving these values meaningful constant names.

Microsoft Learn also recommends avoiding manual string concatenation and control-flow constructs such as if, while, for, and switch in unit tests. Adding logic to a test increases the chance of a bug in the test itself. If the logic seems unavoidable, the recommendation is to split the test into multiple tests.

Turn this insight into action.

Use the mobile app to continue with guided workflows.

To test multiple inputs, Microsoft Learn’s example uses [Theory] and [InlineData]. Each InlineData row pairs an input with its expected result, and the test method verifies the result using Assert.Equal. The same test body runs for each specified case.

Handling dependencies in tests

Microsoft Learn notes that infrastructure dependencies can make unit tests slow and brittle, and recommends reserving those dependencies for integration tests. You can keep unit tests and integration tests in separate projects. This lets the unit test project stay free of references to or dependencies on infrastructure packages.

You can substitute a stub for a dependency. Microsoft Learn defines a stub as a controllable replacement for an existing dependency. With a stub, you can exercise the code under test without interacting directly with the real dependency.

In Microsoft Learn’s .NET terminology, a fake is a general term for an object that can serve as a stub or a mock. Its role depends on how the test uses it. The same fake can act as a stub in one test and as a mock in another.

According to Microsoft Learn, the key distinction is where the test makes its assertions. A test makes assertions against a mock and uses a stub to supply a dependency. For example, if FakeOrder is passed in solely to satisfy a constructor requirement when creating Purchase, it acts as a stub. When the test checks the Validated property on FakeOrder, it acts as a mock.

Terminology varies across the testing literature. Microsoft Learn notes that the classic literature on test doubles also uses narrower definitions. A stub supplies data, a mock verifies interactions, and a fake provides a working alternative implementation. A term’s meaning depends on the context in which it’s used.

Setup and public methods

When tests have different setup requirements, Microsoft Learn recommends creating the necessary objects in each test method or calling a helper method from the test. This way, each test shows the setup it requires and creates only the objects and state it needs.

A shared per-test setup runs before every test in its scope. When tests have different requirements, this setup can create unnecessary objects or obscure the state a particular test depends on. Microsoft Learn notes that shared setup can be appropriate when all tests in a class need the same initial step.

According to Microsoft Learn, private methods are implementation details that operate as part of a larger behavior. You can test the result of the public method that calls the private method. In the example, ParseLogLine processes the input using TrimInput. The test verifies the result of ParseLogLine for input with leading and trailing whitespace.

A private method can return the expected value even when the public method that calls it uses that value incorrectly. Testing the public method’s result verifies the final behavior in this example.

The test pyramid and its limits

Martin Fowler uses the Test Pyramid to describe how to build a balanced suite of automated tests. The pyramid’s main recommendation is to have more low-level unit tests than high-level tests that run through the GUI.

According to Fowler, end-to-end tests that run through the UI can be brittle, expensive to write, and slow to run. A change to the system can break many tests and require recorded tests to be recorded again. End-to-end tests can also produce nondeterministic results, which can reduce confidence in the tests.

The middle layer of the pyramid contains tests that run through the application’s service layer. Fowler calls these SubcutaneousTests. They offer many of the benefits of end-to-end tests while avoiding some of the complexity of working with UI frameworks. In web applications, this layer corresponds to testing through the API.

Fowler also points out that end-to-end scope, use of the UI, and customer-readable specifications are separate characteristics. For example, JavaScript unit tests can verify the behavior of a UI that makes heavy use of JavaScript. Complex business rules can be expressed in a format customers can read and exercised within the relevant module alone.

The pyramid assumes that broad-stack tests are slower, more expensive, and more brittle than focused tests such as unit tests. Fowler points out that there are exceptions. If high-level tests are fast, reliable, and inexpensive to change, lower-level tests may be unnecessary.

Code coverage alone is also insufficient as a measure of quality. According to Microsoft Learn, high coverage tells you how much of the code the unit tests exercise. Determining whether the code is high quality or the testing effort was successful takes more than that figure alone.

Ready to start?

Download the app and continue from your phone.

End of Entry