Common TestNG Assertions
TestNG''s Assert class provides static methods to validate test conditions. A failed assertion throws AssertionError and marks the test as FAILED.
Commonly used assertion methods:
1. assertEquals — Check equality:
Assert.assertEquals(actual, expected);
Assert.assertEquals(driver.getTitle(), "Home Page");
Assert.assertEquals(actual, expected, "Custom failure message");
// Overloaded for: String, int, double, boolean, Object, etc.
2. assertNotEquals — Check inequality:
Assert.assertNotEquals(actual, notExpected);
Assert.assertNotEquals(driver.getTitle(), "Error Page");
3. assertTrue — Check condition is true:
Assert.assertTrue(condition);
Assert.assertTrue(element.isDisplayed(), "Element should be visible");
4. assertFalse — Check condition is false:
Assert.assertFalse(condition);
Assert.assertFalse(errorMsg.isDisplayed(), "No error should appear");
5. assertNull — Check object is null:
Assert.assertNull(object);
Assert.assertNull(driver.findElements(By.id("popup")).isEmpty() ? null : "popup");
6. assertNotNull — Check object is not null:
Assert.assertNotNull(object);
Assert.assertNotNull(driver.findElement(By.id("username")));
7. fail — Force test failure:
Assert.fail("Test deliberately failed");
Assert.fail("Expected exception was not thrown");
Full example:
@Test
public void validateHomePage() {
driver.get("https://example.com");
// Title validation
Assert.assertEquals(driver.getTitle(), "Example Domain");
// Element presence
WebElement heading = driver.findElement(By.tagName("h1"));
Assert.assertNotNull(heading, "Heading should exist");
Assert.assertTrue(heading.isDisplayed(), "Heading should be visible");
// URL check
Assert.assertFalse(driver.getCurrentUrl().contains("error"));
}
Quick reference table:
| Method | Checks |
|---|---|
assertEquals(a, e) | a equals e |
assertNotEquals(a, n) | a does not equal n |
assertTrue(condition) | condition is true |
assertFalse(condition) | condition is false |
assertNull(obj) | obj is null |
assertNotNull(obj) | obj is not null |
fail(msg) | Always fails the test |
