Recall & Review
beginner
What is the purpose of the
@BeforeEach annotation in JUnit?The
@BeforeEach annotation marks a method to be run before each test method. It is used to set up common test data or state so each test starts fresh.Click to reveal answer
beginner
When is a method annotated with
@BeforeEach executed in the test lifecycle?It runs before every individual test method in the test class, ensuring setup code is executed freshly for each test.
Click to reveal answer
intermediate
Can you have multiple
@BeforeEach methods in one test class?Yes, you can have multiple
@BeforeEach methods. They will all run before each test method, but the order is not guaranteed unless explicitly controlled.Click to reveal answer
beginner
Write a simple example of a
@BeforeEach method in JUnit that initializes a list before each test.import org.junit.jupiter.api.BeforeEach;
import java.util.ArrayList;
import java.util.List;
class MyTests {
List<String> items;
@BeforeEach
void setup() {
items = new ArrayList<>();
}
// test methods here
}Click to reveal answer
beginner
Why is using
@BeforeEach better than repeating setup code inside every test method?Using
@BeforeEach avoids duplication, makes tests cleaner, and ensures consistent setup. It helps tests stay independent and easier to maintain.Click to reveal answer
What does the
@BeforeEach annotation do in JUnit?✗ Incorrect
@BeforeEach runs the annotated method before every test method to prepare test data or state.
Can you have more than one
@BeforeEach method in a test class?✗ Incorrect
You can have multiple @BeforeEach methods, but their execution order is not guaranteed unless controlled.
When is a
@BeforeEach method executed?✗ Incorrect
@BeforeEach methods run before each test method to set up the test environment.
Which of these is a good use for
@BeforeEach?✗ Incorrect
@BeforeEach is used to initialize or reset objects before each test runs.
What happens if a
@BeforeEach method throws an exception?✗ Incorrect
If a @BeforeEach method throws an exception, the related test is skipped and marked as failed.
Explain the role of the
@BeforeEach method in JUnit testing and why it is useful.Think about how you prepare for each test to run independently.
You got /4 concepts.
Describe a scenario where using multiple
@BeforeEach methods might be helpful.Imagine you have several independent setup steps before tests.
You got /4 concepts.