Finding Design Flaws with Unit Testing

Explore how each section of a unit test—Arrange, Act, and Assert (AAA)—can reveal potential design flaws, helping developers identify and rectify issues early in the development process.

Our tests are a rich source of feedback on our design. As we make decisions, we write them as test code. Seeing this code—the first usage of our production code—brings into sharp focus how good our proposed design is. When our design isn’t good, the AAA sections of our test will reveal those design issues as code smells in the test. Let’s try to understand in detail how each of these can help identify a faulty design.

Arrange

If the code in our Arrange step is messy, our object might be difficult to create and configure. It might need too many parameters in a constructor or too many optional parameters left as null in the test.

It can be that the object needs too many dependencies injected, indicating that it has too many responsibilities or it might need too many primitive data parameters to pass in a lot of configuration items.

These signal that how we create our object might benefit from a redesign.

Act

Calling the main part of the code in the Act step is usually straightforward, but it can reveal some basic design errors. For example, we might have unclear parameters that we pass in, signatures such as a list of Boolean or String objects. It is very hard to know what each one means.

We could design this by wrapping those difficult parameters in an easy-to-understand new class, called a configuration object.

Another possible problem is if the Act step requires multiple calls to be made in a specific order. That is error-prone. It is easy to call them in the wrong order or forget one of the calls. We could redesign to use a single method that wraps all of this detail.

Assert

The Assert step will reveal whether our code's results are difficult to use. Problem areas might include having to call accessors in a specific order or perhaps returning some conventional code smells, such as an array of results where every index has a different meaning. In either case, we can redesign to use safer constructs.

Get hands-on with 1400+ tech skills courses.