Search⌘ K
AI Features

Focused and Single-purpose Tests

Explore the practice of writing focused and single-purpose unit tests in JUnit. Learn to separate combined test cases into individual tests to enhance test isolation, clarity, and debugging efficiency. Understand benefits such as precise failure identification and comprehensive test execution to improve your Java testing skills.

In order to learn about the importance of a focused, single purpose test, let’s first examine matches in ProfileTest. In this test, we are asserting two things, each of which is prefaced with an explanatory comment.

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 matches() {
      Profile profile = new Profile("Bull Hockey, Inc.");
      Question question = new BooleanQuestion(1, "Got milk?");

      // answers false when must-match criteria not met
      profile.add(new Answer(question, Bool.FALSE));      
      Criteria criteria = new Criteria();
      criteria.add(
            new Criterion(new Answer(question, Bool.TRUE), Weight.MustMatch));

      assertFalse(profile.matches(criteria));
      
      // answers true for any don't care criteria 
      profile.add(new Answer(question, Bool.FALSE));      
      criteria = new Criteria();
      criteria.add(
            new Criterion(new Answer(question, Bool.TRUE), Weight.DontCare));

      assertTrue(profile.matches(criteria));
   }
}
ProfileTest.java

If needed, we could add the rest of the test cases to the matches test with prefaced explanatory comments.

...

...