Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are JUnit 5 lifecycle annotations (@BeforeEach, @BeforeAll, @AfterEach, @AfterAll)? JUnit 5 लाइफसाइकल एनोटेशन (@BeforeEach, @BeforeAll, @AfterEach, @AfterAll) क्या हैं?

Answer

@BeforeEach runs before every individual test method, typically used to reset test data or re-create mocks so tests don't leak state between each other. @AfterEach runs after every test method, used for cleanup like closing resources.

@BeforeAll runs once before all tests in the class (must be static unless the test class uses @TestInstance(Lifecycle.PER_CLASS)), suited for expensive one-time setup like starting a shared Testcontainer. @AfterAll runs once after all tests complete, used for expensive teardown. Choosing the right scope avoids both redundant setup cost and unwanted state leaking between tests.

class OrderServiceTest {
    @BeforeAll
    static void setupOnce() { /* start shared resource */ }

    @BeforeEach
    void setup() { orderService = new OrderService(mockGateway); }

    @AfterEach
    void tearDown() { reset(mockGateway); }
}

@BeforeEach हर व्यक्तिगत टेस्ट मेथड से पहले चलता है, आमतौर पर टेस्ट डेटा रीसेट करने या मॉक्स को फिर से बनाने के लिए उपयोग होता है ताकि टेस्ट के बीच स्टेट लीक न हो। @AfterEach हर टेस्ट मेथड के बाद चलता है, क्लीनअप के लिए उपयोग होता है।

@BeforeAll क्लास के सभी टेस्ट से पहले एक बार चलता है, महंगे एक-बार सेटअप के लिए उपयुक्त है जैसे साझा Testcontainer शुरू करना। @AfterAll सभी टेस्ट पूरे होने के बाद एक बार चलता है।

class OrderServiceTest {
    @BeforeAll
    static void setupOnce() { /* साझा संसाधन शुरू करें */ }

    @BeforeEach
    void setup() { orderService = new OrderService(mockGateway); }
}

Was this answer clear?