More on @Before and @After (Common Initialization and Cleanup)

In Chapter 2, Getting Real with JUnit, you learned how to eliminate duplicate initialization across tests by using an @Before method (sometimes referred to as a setup method).

As you add more tests for a given set of related behaviors, you’ll realize that many of them have the same initialization needs. You’ll want to take advantage of the @Before method to help ensure that your tests don’t become a maintenance nightmare of redundant code.

It’s important to understand the order in which JUnit executes @Before and @Test methods. Here’s a small example:

iloveyouboss/13/test/scratch/AssertTest.java
 
private​ Account account;
 
 
@Before
 
public​ ​void​ createAccount() {
 
account ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.