Initializing Tests with @Before Methods

The first thing to look at is common initialization code in all (both) of the tests in ProfileTest. If both tests have such duplicate logic, move it into an @Before method. For each test JUnit runs, it first executes code in any methods marked with the @Before annotation.

The tests in ProfileTest each require the existence of an initialized Profile object and a new Question object. Move that initialization to an @Before method named create() (or bozo() if you want to irritate your teammates—the name is arbitrary).

iloveyouboss/10/test/iloveyouboss/ProfileTest.java
 
public​ ​class​ ProfileTest {
*
private​ Profile profile;
*
private​ BooleanQuestion question;
*
private​ Criteria criteria;
*
*
@Before
*

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.