Have a question?
Message sent Close
View Categories

Assertions in TestNG

📄
filename.js
Assert.assertTrue(condition);

Assert.assertEquals(actual, expected);

Assert.assertNotNull(object);

📄
filename.js
SoftAssert soft = new SoftAssert();

soft.assertTrue(condition);

// … more soft asserts …

soft.assertAll();  // must call at end to report failures
📄
filename.js
import org.testng.Assert;

import org.testng.annotations.Test;

public class AssertionExamples {

  @Test
 public void hardAssertionTest() {

    int sum = 2 + 2;

    Assert.assertEquals(sum, 4);

    String text = "hello";

    Assert.assertTrue(text.startsWith("h"));

  }

}

📄
filename.js
@Test
public void todayDateTest() {

  String today = getCurrentDate();

  // if this assertion fails, “Date format is wrong” appears in the report

  Assert.assertEquals(today, "2025-07-05", "Date format is wrong");

}

📄
filename.js
import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

public class SoftAssertExample {

  @Test
  public void multipleChecks() {

    SoftAssert soft = new SoftAssert();

    soft.assertTrue(isElementVisible(), "Element should be visible");

    soft.assertEquals(getTitle(), "Dashboard", "Title mismatch");

    soft.assertNotNull(getUser(), "User should be logged in");

    // Reports any failures above; must call or test passes regardless

    soft.assertAll();

  }

  private boolean isElementVisible() { /*…*/ return false; }

  private String getTitle()             { /*…*/ return "";  }

  private Object getUser()              { /*…*/ return null; }

}

📄
filename.js
// org.testng.Assert

Assert.assertTrue(condition, "Optional failure message");

Assert.assertFalse(condition, "Optional failure message");

Assert.assertEquals(actual, expected, "Optional failure message");

Assert.assertNotEquals(actual, expected, "Optional failure message");

Assert.assertNull(object, "Optional failure message");

Assert.assertNotNull(object, "Optional failure message");

Assert.fail("Explicit failure with message");

// org.testng.asserts.SoftAssert

SoftAssert soft = new SoftAssert();

soft.assertTrue(...);

soft.assertFalse(...);

soft.assertEquals(...);

soft.assertAll();