← Back to libraryQuestion 268 of 468
🔬TestNG & JUnitBeginner

Core Annotations and Lifecycle

📌 Definition:

Both frameworks use annotations to mark tests and setup/teardown methods. The lifecycle runs configuration methods around test methods at different scopes (method, class, suite/all).

📖 Detailed Explanation:

TestNG lifecycle: @BeforeSuite/@AfterSuite (once per suite), @BeforeTest/@AfterTest, @BeforeClass/@AfterClass (once per class), @BeforeMethod/@AfterMethod (before/after each @Test). JUnit 5: @BeforeAll/@AfterAll (once per class, static), @BeforeEach/@AfterEach (per test), with @Test marking tests. Use method-level setup (@BeforeMethod/@BeforeEach) to reset state per test for independence, and class/suite-level (@BeforeClass/@BeforeAll) for expensive one-time setup (DB connection, driver reuse). Correct scope choice balances isolation against speed — per-test setup is safest, per-class is faster but risks shared-state leakage.

🔑 Key Points:
  • @Test marks tests; config annotations run around them
  • TestNG: @BeforeSuite/Class/Method; JUnit5: @BeforeAll/@BeforeEach
  • @BeforeMethod/@BeforeEach → per-test isolation
  • @BeforeClass/@BeforeAll → one-time expensive setup
🌍 Real-World Example:

@BeforeMethod resets the app to a known state before each @Test (fresh cart), while @BeforeClass opens one browser reused across the class's tests to save launch time.

🎯 Scenario-Based Interview Question:

Tests pass together but fail in isolation. Which lifecycle mistake commonly causes this, and how do you fix it?