Why does TestNG organize tests using annotations like @BeforeMethod, @Test, and @AfterMethod?
Think about how setup and cleanup code can be reused for each test.
TestNG uses annotations to structure test execution so that setup and cleanup methods run automatically before and after each test. This ensures tests run in a controlled environment and reduces code duplication.
What will be the output order when running this TestNG test class?
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 cleanup() { System.out.println("Cleanup"); } }
Remember that @BeforeMethod and @AfterMethod run before and after each @Test method.
TestNG runs @BeforeMethod before each test method and @AfterMethod after each test method. So for two tests, setup and cleanup run twice, surrounding each test.
Which assertion correctly verifies that a web page title equals "Home Page" in a TestNG Selenium test?
String actualTitle = driver.getTitle();
Check the correct method signature for equality assertion in TestNG.
Assert.assertEquals(actual, expected) is the correct way to check equality in TestNG. Option A uses assignment instead of comparison, C has an invalid third argument, and A ignores case which may not be desired.
Given this TestNG test class, why does the @AfterMethod not run after testLogin?
import org.testng.annotations.*; public class LoginTest { @BeforeMethod public void setup() { System.out.println("Setup"); } @Test public void testLogin() { System.out.println("Login Test"); throw new RuntimeException("Fail"); } @AfterMethod public void cleanup() { System.out.println("Cleanup"); } }
Consider how TestNG handles cleanup when tests throw exceptions.
By default, if a test method throws an exception, @AfterMethod may not run unless it has alwaysRun=true. Adding this attribute ensures cleanup runs even if the test fails.
When TestNG is configured to run tests in parallel by methods, what is the expected behavior regarding @BeforeMethod and @AfterMethod?
Think about thread safety and how setup/cleanup should behave when tests run at the same time.
In parallel execution by methods, TestNG runs each test method in its own thread. The @BeforeMethod and @AfterMethod run in the same thread as their test method, ensuring isolated setup and cleanup.