Verify Google Search page title
Preconditions (3)
✅ Expected Result: The browser opens Google homepage, the title is exactly 'Google', and browser closes after verification
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class GoogleTitleTest { private WebDriver driver; @BeforeMethod public void setUp() { // Initialize ChromeDriver driver = new ChromeDriver(); // Open Google homepage driver.get("https://www.google.com"); } @Test public void verifyGoogleTitle() { // Get the page title String title = driver.getTitle(); // Assert title is exactly 'Google' Assert.assertEquals(title, "Google", "Page title should be 'Google'"); } @AfterMethod public void tearDown() { // Close the browser if (driver != null) { driver.quit(); } } }
The @BeforeMethod annotation marks the setUp() method to run before each test. It initializes the ChromeDriver and opens the Google homepage.
The @Test annotation marks verifyGoogleTitle() as the test method. It fetches the page title and asserts it equals 'Google'.
The @AfterMethod annotation marks tearDown() to run after each test. It closes the browser to clean up.
This structure ensures the browser opens fresh for each test and closes afterward, keeping tests independent and clean.
Now add data-driven testing with 3 different URLs and verify their titles
@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