Search⌘ K
AI Features

Code Refactoring

Explore how to safely refactor unit tests after writing them in the Test-Driven Development cycle. Learn to clean up test code by extracting common setups, renaming variables for clarity, and using helper methods to make tests more readable and maintainable.

We'll cover the following...

Clean Up Tests

After the second pass through the TDD cycle, we have code we can clean up in the tests. We want our tests to stay short and clear. Both our tests instantiate Profile. Create a Profile field and move the common initialization to an @Before method:

package iloveyouboss;

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

public class ProfileTest {
   private Profile profile;

   @Before
   public void createProfile() {
      profile = new Profile();
   }

   @Test
   public void matchesNothingWhenProfileEmpty() {
      Question question = new BooleanQuestion(1, "Relocation package?");
      Criterion criterion = 
         new Criterion(new Answer(question, Bool.TRUE), Weight.DontCare);
      
      boolean result = profile.matches(criterion);
      
      assertFalse(result);
   }
   // ...
}
ProfileTest.java

Rerun the tests to make sure we ...