liveBook · Manning

beforeEach

As explained in Spring Start Here, Second Edition

The @BeforeEach annotation marks a JUnit Jupiter method for execution before each test method.

When each test needs its own setup, annotate a method with JUnit Jupiter’s @BeforeEach. JUnit runs that method before each test, so it can create the objects the test will use. section 15.2

Listing 15.2 Creating the object whose method we want to unit test
public class TransferServiceUnitTests {
 
  private AccountRepository accountRepository;
 
  private TransferService transferService;
 
  @BeforeEach    #A
  void setUp() {
    accountRepository = mock(AccountRepository.class);    #B
    transferService = new TransferService(accountRepository);    #C
  }
 
}

In this transfer-service test, setUp() creates a mock repository and passes it to the service before each test. section 15.2

How Spring Start Here, Second Edition covers it

How deep it goes
Demonstrates the annotation on a setup method that creates a mock repository and service, without detailing other lifecycle behavior.
Examples
Shows a transfer-service test setup that creates a mock AccountRepository and a TransferService.
What you can do after
Apply @BeforeEach in JUnit Jupiter to initialize test objects before each test.
How it connects
Connects unit testing with JUnit Jupiter and Mockito mocks.

Also explained in

Compare how 2 books explain beforeEach →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.