Search⌘ K

Initializing Tests with @Before Methods

Explore how to use the @Before annotation in JUnit to initialize common test data before each test method runs. Understand the execution sequence, enhance test clarity by moving repeated setup code into @Before methods, and learn to refactor tests for improved readability and maintainability.

We'll cover the following...

The @Before annotation is used to denote methods when we need to execute some common code before running a test. The first thing to look at is the common initialization code in all (both) of the tests in ProfileTest.

If both tests have the same logic, we can move that common logic into an @Before method. That way, each JUnit first executes code in any methods marked with the @Before annotation.

package iloveyouboss;

import org.junit.*;
import static org.junit.Assert.*;

public class ProfileTest {
   private Profile profile;
   private BooleanQuestion question;
   private Criteria criteria;
   
   @Before
   public void create() {
      profile = new Profile("Bull Hockey, Inc.");
      question = new BooleanQuestion(1, "Got bonuses?");
      criteria = new Criteria();
   }

   @Test
   public void matchAnswersFalseWhenMustMatchCriteriaNotMet() {
      Answer profileAnswer = new Answer(question, Bool.FALSE);
      profile.add(profileAnswer);      
      Answer criteriaAnswer = new Answer(question, Bool.TRUE);
      Criterion criterion = new Criterion(criteriaAnswer, Weight.MustMatch);
      criteria.add(criterion);

      boolean matches = profile.matches(criteria);
      
      assertFalse(matches);
   }
   
   @Test
   public void matchAnswersTrueForAnyDontCareCriteria() {
      Answer profileAnswer = new Answer(question, Bool.FALSE);
      profile.add(profileAnswer);      
      Answer criteriaAnswer = new Answer(question, Bool.TRUE);
      Criterion criterion = new Criterion(criteriaAnswer, Weight.DontCare);
      criteria.add(criterion);

      boolean matches = profile.matches(criteria);
      
      assertTrue(matches);
   }
}
Tests for profile class

The OK (2 tests) result shows that our tests are passing. ...