import org.testng.annotations.*; public class SampleTest { @BeforeMethod public void setup() { System.out.println("Setup"); } @Test public void testA() { System.out.println("Test A"); } @Test public void testB() { System.out.println("Test B"); } @AfterMethod public void teardown() { System.out.println("Teardown"); } }
TestNG runs @BeforeMethod before each @Test method and @AfterMethod after each @Test method. So for two tests, the sequence is: Setup, Test A, Teardown, Setup, Test B, Teardown.
import org.testng.Assert; import org.testng.annotations.*; public class SetupTest { private boolean setupDone = false; @BeforeMethod public void setup() { setupDone = true; } @Test public void testCheckSetup() { // Which assertion below is correct here? } }
The setup method sets setupDone to true before the test method runs. So inside the test, setupDone should be true. Assert.assertTrue(setupDone) verifies this.
import org.testng.annotations.*; public class DebugTest { @BeforeMethod public void setup() { System.out.println("Setup"); } @Test public void testSomething() { System.out.println("Test"); throw new RuntimeException("Fail"); } @AfterMethod public void teardown() { System.out.println("Teardown"); } }
In TestNG, @AfterMethod runs regardless of whether the test passes or fails. So even if the test throws an exception, teardown should run. The problem is not due to the exception.
@BeforeMethod runs before each test method to prepare the test environment. @AfterMethod runs after each test method to clean up. They do not run once for all tests or depend on test success.
TestNG allows multiple @BeforeMethod methods. It runs all of them before each test method, but the order is not guaranteed unless specified by @Test(priority) or @BeforeMethod(alwaysRun) with dependencies.