It is pretty hard to figure out a good definition for clean code because everyone of us has our own definition for the word clean. However, there is one definition which seems to be universal:
Clean code is easy to read.
This might come as a surprise to some of you, but I think that this definition applies to test code as well. It is in our best interests to make our tests as readable as possible because:
- If our tests are easy to read, it is easy to understand how our code works.
- If our tests are easy to read, it is easy to find the problem if a test fails (without using a debugger).
It isn’t hard to write clean tests, but it takes a lot of practice, and that is why so many developers are struggling with it.
I have struggled with this too, and that is why I decided to share my findings with you.
Introducing: Writing Clean Tests
This tutorial consists of the following blog posts:
- Three Reasons Why We Should Not Use Inheritance In Our Tests describes why we shouldn't use inheritance in our tests.
- Writing Clean Tests – It Starts From the Configuration describes how we can create a clean configuration for our test classes.
- Writing Clean Tests - Naming Matters explains why we should pay attention to naming and describes a few useful naming conventions which will help us to write clean tests.
- Writing Clean Tests - Beware of Magic describes why we shouldn't use magic numbers in our tests and demonstrates how we can improve the readability of our tests by replacing magic numbers with constants.
- Writing Clean Tests - New Considered Harmful explains why we shouldn't create new objects in our test methods by using the new keyword. It also describes how we can create new objects by using factory methods and test data builders.
- Writing Clean Tests – Replace Assertions with a Domain-Specific Language identifies the problems caused by the standard JUnit assertions and describes how we can solve these problems by replacing assertions with a domain-specific language.
- Writing Clean Tests – Divide and Conquer describes why we should write unit tests which have only reason to fail and demonstrates how we can split an existing unit test into multiple tests which test a single logical concept.
- Writing Clean Tests – To Verify Or Not To Verify describes why we should not verify every interaction between the tested code and our mock objects. It also helps us to identify the interactions which we should verify.
- Writing Clean Tests - Trouble in Paradise identifies the most common problems found from "clean" unit tests and describes why we should care about them.
- Writing Clean Tests - Small Is Beautiful describes how we can solve the problems found from "clean" unit tests by using nested inner classes.
- Writing Clean Tests - Java 8 to the Rescue describes how we can catch exceptions and capture method arguments without writing any boilerplate code.