Test Overview
This test uses TestNG annotations to open a browser before each test, check the page title, and close the browser after each test.
This test uses TestNG annotations to open a browser before each test, check the page title, and close the browser after each test.
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestNGAnnotationsExample { WebDriver driver; @BeforeMethod public void setUp() { // Set the path to chromedriver executable if needed // System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); driver = new ChromeDriver(); driver.get("https://example.com"); } @Test public void verifyPageTitle() { String title = driver.getTitle(); assertEquals(title, "Example Domain", "Page title should be 'Example Domain'"); } @AfterMethod public void tearDown() { if (driver != null) { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | BeforeMethod runs: ChromeDriver is initialized and navigates to https://example.com | Browser window opens and loads the Example Domain page | — | PASS |
| 2 | Test method runs: Gets the page title | Browser is on Example Domain page | Check that page title equals 'Example Domain' | PASS |
| 3 | AfterMethod runs: Browser is closed | Browser window closes | — | PASS |
@BeforeMethod annotation in TestNG?@BeforeMethod@Test marks test methods, @AfterMethod runs after each test, and skipping tests uses other annotations.@BeforeMethod = setup before each test [OK]@Test is the correct annotation to mark a method as a test case in TestNG.@Test void testMethod() {} is valid Java and TestNG syntax.@Test marks test methods [OK]public class SampleTest {
@BeforeMethod
public void setup() {
System.out.println("Setup");
}
@Test
public void test1() {
System.out.println("Test1");
}
@Test
public void test2() {
System.out.println("Test2");
}
@AfterMethod
public void cleanup() {
System.out.println("Cleanup");
}
}
What will be the order of printed lines when this test class runs?@Test method, @BeforeMethod runs before it and @AfterMethod runs after it.public class TestExample {
@BeforeMethod
public void setup() {
System.out.println("Setup");
}
@Test
public void testMethod() {
System.out.println("Test");
}
@AfterMethod
public void cleanup() {
System.out.println("Cleanup")
}
}System.out.println("Cleanup") is missing a semicolon at the end.@BeforeClass runs once before any test methods in the class.@AfterMethod runs after each test method to clean up.Pass the test and this pattern moves unknown