0
0
JUnittesting~5 mins

@BeforeEach method in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ARuns a method before each test method
BRuns a method after all tests
CMarks a test method to be ignored
DRuns a method only once before all tests
Can you have more than one @BeforeEach method in a test class?
AYes, but order is not guaranteed
BNo, only one is allowed
CYes, and order is always alphabetical
DNo, it causes a compilation error
When is a @BeforeEach method executed?
AAfter each test method
BBefore all test methods once
COnly if a test fails
DBefore each test method
Which of these is a good use for @BeforeEach?
ACleaning up resources after tests
BInitializing objects needed for tests
CSkipping tests conditionally
DLogging test results
What happens if a @BeforeEach method throws an exception?
AJUnit ignores the exception
BThe test method runs anyway
CThe test method is skipped and marked failed
DAll tests in the class are skipped
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.