Test Smell: Multiple Assertions

We’ve mentioned a few times in this book (one example: F[I]RST: [I]solate Your Tests) that it’s a good idea to move in the direction of a single assert per test. You’ll sometimes find reasons to assert multiple postconditions in a single test, but more often the multiple assertions indicate that you have two test cases.

Our longer test screams, “Split me!” The first case represents finding a search result in the input, and the second case represents finding no match. Split the test into two, providing each with a name that concisely states the expected behavior given the context for the test:

iloveyouboss/test-6/test/util/SearchTest.java
 
public​ ​class​ SearchTest {
 
private​ ​static​ ​final​ ​String​ A_TITLE ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.