Adding Tests First
Learn how writing tests before production code serves as a powerful design tool in test-driven development. Discover how the arrange, act, and assert steps help shape clear interfaces, improve code usability, and provide executable specifications. Understand the balance between code coverage and quality, and why incremental test creation supports continuous delivery and better software design.
In this lesson, we’ll review the trade-offs of adding a test first before writing the production code to make it pass. Previous chapters have followed a test-first approach to writing code. We write a test before writing production code to make that test pass. This is a recommended approach, but it’s important to understand some of the difficulties associated with it as well as consider its benefits.
Test-first is a design tool
The most important benefit of writing tests first is that a test acts as a design aid. As we decide what to write in our test, we’re designing the interface to our code. Each of the test stages helps us consider an aspect of software design, as shown by the following illustration:
The Arrange step helps us think about how the code under test relates to the bigger picture of the whole code base. This step helps us design how the code will fit into the whole code base. It gives us an opportunity to make the following design decisions:
What configuration data will be needed?
What connections to other objects or functions will be needed?
What behavior should this code provide?
What extra inputs are needed to provide that behavior?
Coding the Act step allows us to think about how easy our code will be to use. We reflect on what we’d like the method signature of the code we are designing to be. Ideally, it should be simple and unambiguous. ...