</>

Technology

TestNG

Difficulty

Intermediate

Interview Question

What are some common assertions provided by TestNG?

TestNG assertions include assertEquals, assertNotEquals, assertTrue, assertFalse, assertNull, assertNotNull, and fail() for validating test conditions.

Answer

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:

Java
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:

Java
Assert.assertNotEquals(actual, notExpected);
Assert.assertNotEquals(driver.getTitle(), "Error Page");

3. assertTrue — Check condition is true:

Java
Assert.assertTrue(condition);
Assert.assertTrue(element.isDisplayed(), "Element should be visible");

4. assertFalse — Check condition is false:

Java
Assert.assertFalse(condition);
Assert.assertFalse(errorMsg.isDisplayed(), "No error should appear");

5. assertNull — Check object is null:

Java
Assert.assertNull(object);
Assert.assertNull(driver.findElements(By.id("popup")).isEmpty() ? null : "popup");

6. assertNotNull — Check object is not null:

Java
Assert.assertNotNull(object);
Assert.assertNotNull(driver.findElement(By.id("username")));

7. fail — Force test failure:

Java
Assert.fail("Test deliberately failed");
Assert.fail("Expected exception was not thrown");

Full example:

Java
@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:

MethodChecks
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

Follow AutomateQA

Related Topics