Favor Standalone Tests

 class​ OxygenTankTest {
» OxygenTank tank;
 
» @BeforeEach
 void​ setUp() {
  tank = OxygenTank.withCapacity(10_000);
  tank.fill(5_000);
  }
 
  @Test
 void​ depressurizingEmptiesTank() {
  tank.depressurize();
 
  Assertions.assertTrue(tank.isEmpty());
  }
 
  @Test
 void​ completelyFillTankMustBeFull() {
  tank.fillUp();
 
  Assertions.assertTrue(tank.isFull());
  }
 }

When we are teaching Java, we often see beginners who love to use the @BeforeEach and @BeforeAll annotations. After all, they allow you to extract common setup code that you need in the given part of a test and write it only once. That’s a good thing, because it avoids code duplication. But it comes at a price: setup methods make tests harder to ...

Get Java By Comparison 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.