Popular Searches
Popular Course Categories
Popular Courses

Assertions

TestNG / PyTest

<div class="selenium-notes">

<h1>Assertions in TestNG</h1>

<p>Assertions are one of the most important parts of TestNG-based Selenium automation. An assertion is a validation statement used to compare the actual result produced by an application with the expected result defined by the test case. If the actual result matches the expected condition, the assertion passes. If the expected condition is not satisfied, the assertion fails and TestNG records the test accordingly.</p>

<p>In Selenium automation, WebDriver performs actions such as opening a browser, navigating to a page, entering values, clicking buttons, selecting options, and interacting with web elements. Assertions verify whether those actions produced the expected application behavior.</p>

<p><strong>Course Resource:</strong> <a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a> | <a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

<hr>

<h2>1. What are Assertions?</h2>

<p>An assertion is a validation mechanism provided by TestNG that checks whether an actual value or condition matches the expected result. Assertions are commonly used inside <strong>@Test</strong> methods to determine whether a test scenario has passed or failed.</p>

<pre><code>Assert.assertEquals(actual, expected);</code></pre>

<p>For example, if the expected page title is <strong>Login Page</strong> and the actual page title is also <strong>Login Page</strong>, the assertion passes.</p>

<pre><code>String actualTitle = "Login Page";

String expectedTitle = "Login Page";

 

Assert.assertEquals(actualTitle, expectedTitle);</code></pre>

<hr>

<h2>2. Why are Assertions Important in Selenium?</h2>

<p>Selenium performs browser automation, but simply performing browser actions does not prove that the application behaved correctly. Assertions provide the validation layer that determines whether the expected behavior actually occurred.</p>

<ul>

<li>Validate expected application behavior.</li>

<li>Compare actual and expected values.</li>

<li>Verify page titles.</li>

<li>Verify URLs.</li>

<li>Verify text messages.</li>

<li>Verify element visibility.</li>

<li>Verify element state.</li>

<li>Verify login results.</li>

<li>Verify search results.</li>

<li>Verify cart contents.</li>

<li>Verify form validation messages.</li>

<li>Verify navigation behavior.</li>

<li>Mark test cases as passed or failed.</li>

<li>Improve automation reliability and reporting.</li>

</ul>

<hr>

<h2>3. Assertion Flow in Selenium Automation</h2>

<pre><code>Test Method

     |

     v

Perform Selenium Action

     |

     v

Capture Actual Result

     |

     v

Define Expected Result

     |

     v

Perform Assertion

     |

     +------------------+

     |                  |

     v                  v

Condition True     Condition False

     |                  |

     v                  v

   PASS               FAIL</code></pre>

<hr>

<h2>4. TestNG Assert Class</h2>

<p>TestNG provides the <strong>Assert</strong> class for performing hard assertions.</p>

<pre><code>import org.testng.Assert;</code></pre>

<p>The most commonly used TestNG assertions include:</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Assertion</th><th>Purpose</th></tr>

<tr><td>assertEquals()</td><td>Checks whether two values are equal.</td></tr>

<tr><td>assertNotEquals()</td><td>Checks whether two values are different.</td></tr>

<tr><td>assertTrue()</td><td>Checks whether a condition is true.</td></tr>

<tr><td>assertFalse()</td><td>Checks whether a condition is false.</td></tr>

<tr><td>assertNull()</td><td>Checks whether a value is null.</td></tr>

<tr><td>assertNotNull()</td><td>Checks whether a value is not null.</td></tr>

<tr><td>assertSame()</td><td>Checks whether two references point to the same object.</td></tr>

<tr><td>assertNotSame()</td><td>Checks whether two references point to different objects.</td></tr>

</table>

<hr>

<h2>5. Basic assertEquals()</h2>

<p><strong>assertEquals()</strong> compares two values and passes when the expected and actual values are equal.</p>

<pre><code>import org.testng.Assert;

import org.testng.annotations.Test;

 

public class AssertionTest {

 

    @Test

    public void verifyTitle() {

        String actualTitle = "Login Page";

        String expectedTitle = "Login Page";

 

        Assert.assertEquals(actualTitle, expectedTitle);

    }

}</code></pre>

<p>Here, the actual title and expected title are the same, so the assertion passes.</p>

<hr>

<h2>6. assertEquals() with Numbers</h2>

<pre><code>@Test

public void verifyCalculation() {

    int actual = 100;

    int expected = 100;

 

    Assert.assertEquals(actual, expected);

}</code></pre>

<p>This assertion verifies that both numeric values are equal.</p>

<hr>

<h2>7. assertEquals() with Strings</h2>

<pre><code>@Test

public void verifyMessage() {

    String actualMessage = "Login successful";

    String expectedMessage = "Login successful";

 

    Assert.assertEquals(actualMessage, expectedMessage);

}</code></pre>

<p>This is commonly used for validating confirmation messages, error messages, headings, labels, and other text values.</p>

<hr>

<h2>8. assertNotEquals()</h2>

<p><strong>assertNotEquals()</strong> verifies that two values are not equal.</p>

<pre><code>@Test

public void verifyDifferentValues() {

    String actualStatus = "Active";

    String unexpectedStatus = "Inactive";

 

    Assert.assertNotEquals(actualStatus, unexpectedStatus);

}</code></pre>

<p>The assertion passes because the two values are different.</p>

<hr>

<h2>9. assertTrue()</h2>

<p><strong>assertTrue()</strong> verifies that a Boolean condition is true.</p>

<pre><code>@Test

public void verifyLogin() {

    boolean loginSuccessful = true;

 

    Assert.assertTrue(loginSuccessful);

}</code></pre>

<p>This assertion is particularly useful in Selenium when verifying conditions such as element visibility, URL content, page state, or other Boolean conditions.</p>

<hr>

<h2>10. Selenium Example with assertTrue()</h2>

<pre><code>import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class GoogleTest {

 

    @Test

    public void verifyGoogleTitle() {

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.get("https://www.google.com");

 

            String title = driver.getTitle();

 

            Assert.assertTrue(title.contains("Google"));

        } finally {

            driver.quit();

        }

    }

}</code></pre>

<p>The assertion checks whether the page title contains the word <strong>Google</strong>.</p>

<hr>

<h2>11. assertFalse()</h2>

<p><strong>assertFalse()</strong> verifies that a Boolean condition is false.</p>

<pre><code>@Test

public void verifyLoginButtonState() {

    boolean condition = false;

 

    Assert.assertFalse(condition);

}</code></pre>

<p>In Selenium, this can be useful when verifying that an element is not selected, a condition is not active, or an expected negative condition is satisfied.</p>

<hr>

<h2>12. assertNull()</h2>

<p><strong>assertNull()</strong> verifies that a reference or value is null.</p>

<pre><code>@Test

public void verifyNullValue() {

    String value = null;

 

    Assert.assertNull(value);

}</code></pre>

<p>This type of assertion is generally more common in API, Java, and framework-level validations than in direct UI validation.</p>

<hr>

<h2>13. assertNotNull()</h2>

<p><strong>assertNotNull()</strong> verifies that a value or object is not null.</p>

<pre><code>@Test

public void verifyObject() {

    String username = "admin";

 

    Assert.assertNotNull(username);

}</code></pre>

<p>It can be useful when validating that an object, response, page object, or test data value has been initialized.</p>

<hr>

<h2>14. assertSame()</h2>

<p><strong>assertSame()</strong> verifies that two references point to the same object.</p>

<pre><code>@Test

public void verifySameObject() {

    String value = "Selenium";

    String sameReference = value;

 

    Assert.assertSame(value, sameReference);

}</code></pre>

<p>This assertion checks object identity rather than simply checking whether two values contain the same text.</p>

<hr>

<h2>15. assertNotSame()</h2>

<p><strong>assertNotSame()</strong> verifies that two references do not point to the same object.</p>

<pre><code>@Test

public void verifyDifferentObjects() {

    String first = new String("Selenium");

    String second = new String("Selenium");

 

    Assert.assertNotSame(first, second);

}</code></pre>

<p>The two objects contain the same text but are separate object references.</p>

<hr>

<h2>16. Hard Assertions</h2>

<p>TestNG's standard <strong>Assert</strong> methods are hard assertions. When a hard assertion fails, the current test method stops executing from that point.</p>

<pre><code>@Test

public void verifyPage() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    System.out.println("This line executes only if the assertion passes.");

}</code></pre>

<p>If the assertion fails, the statement after it is not executed within that test method.</p>

<hr>

<h2>17. Hard Assertion Execution Flow</h2>

<pre><code>Test Method

     |

     v

Assertion 1

     |

     +-- PASS --> Continue

     |

     +-- FAIL --> Stop Current Test Method

                      |

                      v

                    FAIL</code></pre>

<hr>

<h2>18. Multiple Hard Assertions</h2>

<pre><code>@Test

public void verifyDashboard() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("logout")).isDisplayed()

    );

}</code></pre>

<p>If the first assertion fails, the remaining statements in the current test method are not executed.</p>

<hr>

<h2>19. Soft Assertions</h2>

<p>Soft assertions allow multiple validations to execute even when one validation fails. TestNG provides the <strong>SoftAssert</strong> class for this purpose.</p>

<pre><code>import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

 

public class DashboardTest {

 

    @Test

    public void verifyDashboard() {

        SoftAssert softAssert = new SoftAssert();

 

        softAssert.assertEquals("Dashboard", "Dashboard");

        softAssert.assertTrue(true);

        softAssert.assertEquals("User", "Admin");

 

        softAssert.assertAll();

    }

}</code></pre>

<p>The test can continue after an individual soft assertion failure. The collected failures are evaluated when <strong>assertAll()</strong> is called.</p>

<hr>

<h2>20. Importance of assertAll()</h2>

<p><strong>assertAll()</strong> is essential when using TestNG SoftAssert. It evaluates the collected assertion failures and causes the test to fail if one or more soft assertions failed.</p>

<pre><code>SoftAssert softAssert = new SoftAssert();

 

softAssert.assertTrue(true);

softAssert.assertEquals("Login", "Login");

softAssert.assertEquals("Dashboard", "Home");

 

softAssert.assertAll();</code></pre>

<p>Without <strong>assertAll()</strong>, the collected soft assertion failures may not cause the test method to be reported as failed.</p>

<hr>

<h2>21. Hard Assertion vs Soft Assertion</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Hard Assertion</th><th>Soft Assertion</th></tr>

<tr><td>Class</td><td>Assert</td><td>SoftAssert</td></tr>

<tr><td>Execution after failure</td><td>Stops current test method.</td><td>Continues with subsequent statements.</td></tr>

<tr><td>Multiple validations</td><td>Later validations may not execute after failure.</td><td>Multiple validations can be collected.</td></tr>

<tr><td>Finalization</td><td>No assertAll() required.</td><td>assertAll() is required.</td></tr>

<tr><td>Typical use</td><td>Critical validation.</td><td>Multiple independent validations on one page.</td></tr>

</table>

<hr>

<h2>22. Selenium Login Assertion</h2>

<p>Assertions are frequently used to verify whether a login operation produced the expected result.</p>

<pre><code>import org.openqa.selenium.By;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class LoginTest extends BaseTest {

 

    @Test

    public void verifyValidLogin() {

        driver.findElement(By.id("username"))

              .sendKeys("admin");

 

        driver.findElement(By.id("password"))

              .sendKeys("admin123");

 

        driver.findElement(By.id("login"))

              .click();

 

        Assert.assertTrue(

            driver.getCurrentUrl().contains("dashboard")

        );

    }

}</code></pre>

<p>Here Selenium performs the login actions and TestNG verifies whether the browser navigated to the expected dashboard.</p>

<hr>

<h2>23. Assertion for Page Title</h2>

<pre><code>@Test

public void verifyPageTitle() {

    driver.get("https://example.com");

 

    String actualTitle = driver.getTitle();

 

    Assert.assertEquals(

        actualTitle,

        "Example Domain"

    );

}</code></pre>

<p>Page-title assertions are useful for verifying navigation and page identity.</p>

<hr>

<h2>24. Assertion for Current URL</h2>

<pre><code>@Test

public void verifyURL() {

    driver.get("https://example.com/login");

 

    String actualURL = driver.getCurrentUrl();

 

    Assert.assertTrue(

        actualURL.contains("/login")

    );

}</code></pre>

<p>This validates that the browser is currently on the expected application route.</p>

<hr>

<h2>25. Assertion for WebElement Visibility</h2>

<pre><code>@Test

public void verifyLoginButton() {

    boolean displayed =

        driver.findElement(By.id("login")).isDisplayed();

 

    Assert.assertTrue(displayed);

}</code></pre>

<p>This verifies that the login button is visible to the user.</p>

<hr>

<h2>26. Assertion for WebElement Enabled State</h2>

<pre><code>@Test

public void verifyButtonEnabled() {

    boolean enabled =

        driver.findElement(By.id("login")).isEnabled();

 

    Assert.assertTrue(enabled);

}</code></pre>

<p><strong>isEnabled()</strong> can be used to verify whether an element is enabled for interaction.</p>

<hr>

<h2>27. Assertion for Checkbox Selection</h2>

<pre><code>@Test

public void verifyCheckboxSelected() {

    boolean selected =

        driver.findElement(By.id("terms")).isSelected();

 

    Assert.assertTrue(selected);

}</code></pre>

<p>This is useful for validating checkbox and radio-button states.</p>

<hr>

<h2>28. Assertion for Text</h2>

<pre><code>@Test

public void verifyWelcomeMessage() {

    String actualMessage =

        driver.findElement(By.id("welcome")).getText();

 

    Assert.assertEquals(

        actualMessage,

        "Welcome, Admin"

    );

}</code></pre>

<p>Text assertions are commonly used for headings, success messages, error messages, notifications, labels, and validation messages.</p>

<hr>

<h2>29. Assertion for Error Message</h2>

<pre><code>@Test

public void verifyInvalidLoginMessage() {

    driver.findElement(By.id("username"))

          .sendKeys("wrong");

 

    driver.findElement(By.id("password"))

          .sendKeys("wrong123");

 

    driver.findElement(By.id("login"))

          .click();

 

    String message =

        driver.findElement(By.id("error"))

              .getText();

 

    Assert.assertEquals(

        message,

        "Invalid username or password"

    );

}</code></pre>

<hr>

<h2>30. Assertion for Element Presence</h2>

<p>When validating that an element exists, Selenium operations should be handled carefully because <strong>findElement()</strong> throws an exception when the element cannot be found.</p>

<pre><code>@Test

public void verifySearchBox() {

    Assert.assertTrue(

        driver.findElement(By.id("search")).isDisplayed()

    );

}</code></pre>

<p>For more flexible presence checks, a framework can use <strong>findElements()</strong> and verify that the returned collection is not empty.</p>

<pre><code>@Test

public void verifySearchBoxExists() {

    boolean exists =

        !driver.findElements(By.id("search")).isEmpty();

 

    Assert.assertTrue(exists);

}</code></pre>

<hr>

<h2>31. Assertion with Custom Message</h2>

<p>TestNG assertion methods can include a message that helps explain the reason for a failure.</p>

<pre><code>@Test

public void verifyTitle() {

    String actualTitle = driver.getTitle();

 

    Assert.assertEquals(

        actualTitle,

        "Dashboard",

        "Dashboard page title is incorrect"

    );

}</code></pre>

<p>Custom assertion messages can make reports and debugging easier.</p>

<hr>

<h2>32. Assertion with Selenium Waits</h2>

<p>Assertions should normally be performed after the application reaches the required state. Selenium waits can be used to synchronize the test before validation.</p>

<pre><code>WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement dashboard =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("dashboard")

        )

    );

 

Assert.assertTrue(dashboard.isDisplayed());</code></pre>

<p>The wait handles synchronization, while the assertion validates the resulting condition.</p>

<hr>

<h2>33. Wait vs Assertion</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Feature</th><th>Wait</th><th>Assertion</th></tr>

<tr><td>Purpose</td><td>Synchronizes test execution with application state.</td><td>Validates the expected result.</td></tr>

<tr><td>Main Question</td><td>Is the application ready?</td><td>Is the result correct?</td></tr>

<tr><td>Example</td><td>Wait until element is visible.</td><td>Assert that element is displayed.</td></tr>

<tr><td>Failure Meaning</td><td>Required condition was not reached within the wait.</td><td>Actual result did not satisfy the expected condition.</td></tr>

</table>

<hr>

<h2>34. Assertions in Arrange-Act-Assert Pattern</h2>

<pre><code>@Test

public void verifyLogin() {

    // Arrange

    String username = "admin";

    String password = "admin123";

 

    // Act

    loginPage.enterUsername(username);

    loginPage.enterPassword(password);

    loginPage.clickLogin();

 

    // Assert

    Assert.assertTrue(

        homePage.isDashboardDisplayed()

    );

}</code></pre>

<p>The assertion is normally placed in the <strong>Assert</strong> section of the test method.</p>

<hr>

<h2>35. Multiple Assertions in a Test</h2>

<p>Multiple assertions can be used when a single test scenario requires several related validations.</p>

<pre><code>@Test

public void verifyDashboard() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("welcome")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("logout")).isDisplayed()

    );

}</code></pre>

<p>However, excessive assertions covering unrelated business scenarios can make a test difficult to understand. Related validations should generally remain together.</p>

<hr>

<h2>36. SoftAssert Example for Dashboard</h2>

<pre><code>import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

 

public class DashboardTest extends BaseTest {

 

    @Test

    public void verifyDashboardElements() {

        SoftAssert softAssert = new SoftAssert();

 

        softAssert.assertEquals(

            driver.getTitle(),

            "Dashboard"

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("logo")).isDisplayed()

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("profile")).isDisplayed()

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("logout")).isDisplayed()

        );

 

        softAssert.assertAll();

    }

}</code></pre>

<hr>

<h2>37. Assertions and Test Results</h2>

<pre><code>Test Method

     |

     v

Perform Action

     |

     v

Capture Actual Result

     |

     v

Assertion

     |

     +----------------+

     |                |

     v                v

   PASS             FAIL

     |                |

     v                v

Continue         Test Failure

     |                |

     +--------+-------+

              |

              v

         Test Report</code></pre>

<hr>

<h2>38. Assertion Failure Example</h2>

<pre><code>@Test

public void verifyTitle() {

    String actualTitle = "Home Page";

    String expectedTitle = "Login Page";

 

    Assert.assertEquals(actualTitle, expectedTitle);

 

    System.out.println("This line will not execute.");

}</code></pre>

<p>Because the actual value and expected value are different, the assertion fails and execution of the current test method stops at that assertion.</p>

<hr>

<h2>39. Assertion and Exception</h2>

<p>Assertions and exceptions are different concepts. An assertion intentionally validates a condition, while an exception indicates an unexpected or exceptional condition during execution.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Concept</th><th>Meaning</th></tr>

<tr><td>Assertion</td><td>Checks whether an expected condition is satisfied.</td></tr>

<tr><td>Exception</td><td>Represents an abnormal condition during program execution.</td></tr>

<tr><td>Example Assertion</td><td>Assert.assertEquals(actual, expected)</td></tr>

<tr><td>Example Exception</td><td>NoSuchElementException</td></tr>

</table>

<hr>

<h2>40. Assertion vs Verification</h2>

<p>In modern TestNG automation, assertions are used to explicitly validate test results. The word "verification" is often used more generally to describe the act of checking whether an expected condition has been met.</p>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Term</th><th>Meaning</th></tr>

<tr><td>Assertion</td><td>A TestNG validation mechanism that can determine test success or failure.</td></tr>

<tr><td>Verification</td><td>The broader testing activity of checking an expected behavior or result.</td></tr>

</table>

<hr>

<h2>41. Assertions with Page Object Model</h2>

<p>In a Page Object Model framework, page classes can expose meaningful methods or state information while test classes perform the final business assertions.</p>

<pre><code>public class LoginPage {

    private WebDriver driver;

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username).sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password).sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}</code></pre>

<h3>Test Method</h3>

<pre><code>@Test

public void verifyValidLogin() {

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.enterUsername("admin");

    loginPage.enterPassword("admin123");

    loginPage.clickLogin();

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

}</code></pre>

<hr>

<h2>42. Assertions with Reusable Page Methods</h2>

<p>A page object can also provide methods that return Boolean values or actual values to the test method.</p>

<pre><code>public boolean isDashboardDisplayed() {

    return driver.findElement(

        By.id("dashboard")

    ).isDisplayed();

}</code></pre>

<p>The test method can then perform the assertion:</p>

<pre><code>@Test

public void verifyDashboard() {

    Assert.assertTrue(

        homePage.isDashboardDisplayed()

    );

}</code></pre>

<hr>

<h2>43. Assertion for Dropdown Selection</h2>

<pre><code>Select country =

    new Select(driver.findElement(By.id("country")));

 

country.selectByVisibleText("India");

 

String selected =

    country.getFirstSelectedOption().getText();

 

Assert.assertEquals(selected, "India");</code></pre>

<p>This verifies that the expected dropdown option was selected.</p>

<hr>

<h2>44. Assertion for Checkbox State</h2>

<pre><code>WebElement checkbox =

    driver.findElement(By.id("terms"));

 

checkbox.click();

 

Assert.assertTrue(

    checkbox.isSelected(),

    "Terms checkbox should be selected"

);</code></pre>

<hr>

<h2>45. Assertion for Button State</h2>

<pre><code>WebElement submitButton =

    driver.findElement(By.id("submit"));

 

Assert.assertTrue(

    submitButton.isEnabled(),

    "Submit button should be enabled"

);</code></pre>

<hr>

<h2>46. Assertion for URL After Navigation</h2>

<pre><code>driver.findElement(By.id("login")).click();

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("dashboard"),

    "User was not redirected to dashboard"

);</code></pre>

<hr>

<h2>47. Assertion for Page Source Content</h2>

<pre><code>String pageSource = driver.getPageSource();

 

Assert.assertTrue(

    pageSource.contains("Welcome"),

    "Welcome text was not found in page source"

);</code></pre>

<p>Page-source assertions can be useful in some situations, but direct element-based validation is generally clearer when a specific UI element can be located reliably.</p>

<hr>

<h2>48. Assertion for Attribute Value</h2>

<pre><code>String placeholder =

    driver.findElement(By.id("username"))

          .getAttribute("placeholder");

 

Assert.assertEquals(

    placeholder,

    "Enter username"

);</code></pre>

<p>This is useful for validating HTML attributes such as placeholder, value, class, href, title, and other relevant attributes.</p>

<hr>

<h2>49. Assertion for Multiple Related UI Elements</h2>

<pre><code>@Test

public void verifyLoginPage() {

    Assert.assertTrue(

        driver.findElement(By.id("username")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("password")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("login")).isDisplayed()

    );

}</code></pre>

<p>These assertions verify that the important controls on the login page are available.</p>

<hr>

<h2>50. SoftAssert for Multiple UI Validations</h2>

<pre><code>@Test

public void verifyLoginPageElements() {

    SoftAssert softAssert = new SoftAssert();

 

    softAssert.assertTrue(

        driver.findElement(By.id("username")).isDisplayed()

    );

 

    softAssert.assertTrue(

        driver.findElement(By.id("password")).isDisplayed()

    );

 

    softAssert.assertTrue(

        driver.findElement(By.id("login")).isDisplayed()

    );

 

    softAssert.assertAll();

}</code></pre>

<p>Soft assertions can be useful when you want to collect several independent UI validation failures from the same page before reporting the final result.</p>

<hr>

<h2>51. Assertion Messages and Debugging</h2>

<p>Adding meaningful assertion messages can make failed automation tests easier to understand.</p>

<pre><code>Assert.assertEquals(

    actualTitle,

    expectedTitle,

    "Page title does not match the expected title"

);</code></pre>

<p>A good assertion message should describe what was expected or what business condition failed.</p>

<hr>

<h2>52. Common Mistakes with Assertions</h2>

<h3>Mistake 1: Performing Actions Without Validation</h3>

<pre><code>@Test

public void loginTest() {

    driver.findElement(By.id("login")).click();

 

    // No validation

}</code></pre>

<p>A test that only performs actions may not prove that the expected result occurred.</p>

<h3>Correct Approach</h3>

<pre><code>@Test

public void loginTest() {

    driver.findElement(By.id("login")).click();

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

}</code></pre>

<h3>Mistake 2: Using the Wrong Expected Value</h3>

<pre><code>Assert.assertEquals(

    actualTitle,

    "Incorrect Title"

);</code></pre>

<p>The expected value should come from the intended test requirement.</p>

<h3>Mistake 3: Forgetting assertAll()</h3>

<pre><code>SoftAssert softAssert = new SoftAssert();

 

softAssert.assertTrue(false);

 

// Missing assertAll()</code></pre>

<p>Always call <strong>assertAll()</strong> after completing the relevant soft validations.</p>

<h3>Mistake 4: Using Hard Assertions for Unrelated Checks</h3>

<p>If several independent page elements need to be validated and you want all validation failures reported together, SoftAssert may be more appropriate.</p>

<h3>Mistake 5: Confusing Waits with Assertions</h3>

<p>A wait synchronizes the test with application state. An assertion validates whether the resulting state is correct. They solve different problems.</p>

<h3>Mistake 6: Using Assertions Before the Page Is Ready</h3>

<p>If an application is dynamic, synchronize with the appropriate condition before validating the result.</p>

<h3>Mistake 7: Using Weak Assertions</h3>

<pre><code>Assert.assertTrue(true);</code></pre>

<p>This does not validate the application. Assertions should be based on meaningful actual application data or state.</p>

<hr>

<h2>53. Best Practices for Assertions</h2>

<ul>

<li>Always validate the important expected outcome of a test.</li>

<li>Use the most specific assertion available.</li>

<li>Keep expected values clear and meaningful.</li>

<li>Use descriptive assertion messages where helpful.</li>

<li>Use hard assertions for critical checkpoints.</li>

<li>Use SoftAssert when several independent validations need to be collected.</li>

<li>Always call <strong>assertAll()</strong> when using SoftAssert.</li>

<li>Synchronize dynamic pages before validating them.</li>

<li>Do not replace proper waits with arbitrary Thread.sleep() calls.</li>

<li>Keep assertions close to the behavior they validate.</li>

<li>Avoid unnecessary assertions that do not add test value.</li>

<li>Keep test data and expected results maintainable.</li>

<li>Use Page Object Model to keep Selenium implementation organized.</li>

<li>Use meaningful failure messages for important business validations.</li>

</ul>

<hr>

<h2>54. Assertion Strategy in Selenium Framework</h2>

<pre><code>Test Case

    |

    v

Open Application

    |

    v

Perform Action

    |

    v

Wait for Required State

    |

    v

Capture Actual Result

    |

    v

Compare with Expected Result

    |

    v

TestNG Assertion

    |

    +-- PASS

    |

    +-- FAIL

    |

    v

Report</code></pre>

<hr>

<h2>55. Assertions in a Real Login Framework</h2>

<pre><code>BaseTest

    |

    +-- Start WebDriver

    |

    v

LoginPage

    |

    +-- Enter Username

    +-- Enter Password

    +-- Click Login

    |

    v

HomePage

    |

    +-- Capture Dashboard State

    |

    v

TestNG Assertion

    |

    +-- Expected = Dashboard

    +-- Actual = Dashboard

    |

    v

PASS</code></pre>

<hr>

<h2>56. Assertions and TestNG Reporting</h2>

<p>Assertion results contribute to the overall TestNG test result. When an assertion fails, TestNG records the corresponding test method as failed unless the failure is handled through an expected exception or another framework-specific mechanism.</p>

<pre><code>Assertion

    |

    +-- Pass

    |     |

    |     v

    |   Test Continues

    |

    +-- Fail

          |

          v

      Test Method Fails

          |

          v

        Report</code></pre>

<hr>

<h2>57. Assertions with Data-Driven Testing</h2>

<p>Assertions can be combined with DataProvider to validate multiple input combinations.</p>

<pre><code>@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123", true},

        {"wrong", "wrong123", false},

        {"tester", "test123", true}

    };

}

 

@Test(dataProvider = "loginData")

public void verifyLogin(

        String username,

        String password,

        boolean expectedSuccess) {

 

    // Perform login

 

    boolean actualSuccess =

        driver.getCurrentUrl().contains("dashboard");

 

    Assert.assertEquals(

        actualSuccess,

        expectedSuccess

    );

}</code></pre>

<p>This approach allows one test method to validate multiple test-data combinations.</p>

<hr>

<h2>58. Assertions with Negative Testing</h2>

<p>Assertions are also important for negative testing. A negative test verifies that the application correctly rejects invalid input or prevents an invalid operation.</p>

<pre><code>@Test

public void verifyInvalidLogin() {

    driver.findElement(By.id("username"))

          .sendKeys("wrongUser");

 

    driver.findElement(By.id("password"))

          .sendKeys("wrongPassword");

 

    driver.findElement(By.id("login"))

          .click();

 

    String errorMessage =

        driver.findElement(By.id("error"))

              .getText();

 

    Assert.assertEquals(

        errorMessage,

        "Invalid username or password"

    );

}</code></pre>

<hr>

<h2>59. Assertions with Expected Exceptions</h2>

<p>TestNG can also validate that a specific exception is expected from a test method.</p>

<pre><code>@Test(expectedExceptions = ArithmeticException.class)

public void verifyExpectedException() {

    int result = 10 / 0;

}</code></pre>

<p>In this case, the exception is part of the expected test behavior.</p>

<hr>

<h2>60. Assertion Methods Quick Reference</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Method</th><th>Example</th><th>Purpose</th></tr>

<tr><td>assertEquals()</td><td>Assert.assertEquals(actual, expected)</td><td>Checks equality.</td></tr>

<tr><td>assertNotEquals()</td><td>Assert.assertNotEquals(actual, unexpected)</td><td>Checks inequality.</td></tr>

<tr><td>assertTrue()</td><td>Assert.assertTrue(condition)</td><td>Checks that condition is true.</td></tr>

<tr><td>assertFalse()</td><td>Assert.assertFalse(condition)</td><td>Checks that condition is false.</td></tr>

<tr><td>assertNull()</td><td>Assert.assertNull(value)</td><td>Checks that value is null.</td></tr>

<tr><td>assertNotNull()</td><td>Assert.assertNotNull(value)</td><td>Checks that value is not null.</td></tr>

<tr><td>assertSame()</td><td>Assert.assertSame(first, second)</td><td>Checks object identity.</td></tr>

<tr><td>assertNotSame()</td><td>Assert.assertNotSame(first, second)</td><td>Checks different object references.</td></tr>

</table>

<hr>

<h2>61. Hard Assert vs SoftAssert Syntax</h2>

<h3>Hard Assertion</h3>

<pre><code>Assert.assertEquals(

    actual,

    expected

);</code></pre>

<h3>Soft Assertion</h3>

<pre><code>SoftAssert softAssert = new SoftAssert();

 

softAssert.assertEquals(

    actual,

    expected

);

 

softAssert.assertAll();</code></pre>

<hr>

<h2>62. Practical E-Commerce Assertions</h2>

<pre><code>@Test

public void verifyProductAddedToCart() {

    productPage.searchProduct("Laptop");

 

    productPage.addProductToCart();

 

    String cartCount =

        cartPage.getCartItemCount();

 

    Assert.assertEquals(

        cartCount,

        "1",

        "Cart should contain one product"

    );

}</code></pre>

<h3>Checkout Validation</h3>

<pre><code>@Test

public void verifyCheckoutPage() {

    cartPage.clickCheckout();

 

    Assert.assertTrue(

        checkoutPage.isCheckoutPageDisplayed(),

        "Checkout page should be displayed"

    );

}</code></pre>

<hr>

<h2>63. Practical Registration Assertions</h2>

<pre><code>@Test

public void verifyRegistrationSuccess() {

    registrationPage.enterName("John");

    registrationPage.enterEmail("[email protected]");

    registrationPage.enterPassword("Password123");

    registrationPage.clickRegister();

 

    String message =

        registrationPage.getSuccessMessage();

 

    Assert.assertEquals(

        message,

        "Registration successful"

    );

}</code></pre>

<hr>

<h2>64. Practical Form Validation Assertions</h2>

<pre><code>@Test

public void verifyRequiredFieldValidation() {

    registrationPage.clickRegister();

 

    String error =

        registrationPage.getEmailErrorMessage();

 

    Assert.assertEquals(

        error,

        "Email is required"

    );

}</code></pre>

<hr>

<h2>65. Practical Assertion Framework Structure</h2>

<pre><code>src/test/java

    |

    +-- tests

    |     |

    |     +-- LoginTest.java

    |     +-- RegistrationTest.java

    |     +-- SearchTest.java

    |     +-- CheckoutTest.java

    |

    +-- pages

    |     |

    |     +-- LoginPage.java

    |     +-- HomePage.java

    |     +-- CartPage.java

    |     +-- CheckoutPage.java

    |

    +-- base

    |     |

    |     +-- BaseTest.java

    |

    +-- utilities

          |

          +-- WaitUtils.java

          +-- ScreenshotUtils.java</code></pre>

<p>Test classes perform business validations, page classes expose page functionality, and reusable utilities handle common framework operations.</p>

<hr>

<h2>66. Assertion Execution Flow in a Real Project</h2>

<pre><code>testng.xml

     |

     v

TestNG

     |

     v

@Test Method

     |

     v

Selenium Action

     |

     v

Synchronization

     |

     v

Actual Result

     |

     v

Expected Result

     |

     v

Assertion

     |

     +-- PASS

     |

     +-- FAIL

     |

     v

Test Report

     |

     +-- Logs

     +-- Screenshot

     +-- Failure Details</code></pre>

<hr>

<h2>67. Common Interview Questions on Assertions</h2>

<h3>Q1. What is an assertion in TestNG?</h3>

<p>An assertion is a validation mechanism used to compare actual application behavior with the expected result.</p>

<h3>Q2. Why are assertions used in Selenium?</h3>

<p>Selenium performs browser actions, while assertions verify whether the application produced the expected result.</p>

<h3>Q3. What is the difference between assertEquals() and assertTrue()?</h3>

<p><strong>assertEquals()</strong> compares two values, while <strong>assertTrue()</strong> checks whether a Boolean condition is true.</p>

<h3>Q4. What is assertFalse()?</h3>

<p><strong>assertFalse()</strong> verifies that a Boolean condition evaluates to false.</p>

<h3>Q5. What is assertNotNull()?</h3>

<p>It verifies that the supplied value or object is not null.</p>

<h3>Q6. What is a hard assertion?</h3>

<p>A hard assertion stops execution of the current test method when the assertion fails.</p>

<h3>Q7. What is SoftAssert?</h3>

<p>SoftAssert allows multiple assertions to be collected while allowing the test method to continue executing.</p>

<h3>Q8. Why is assertAll() required with SoftAssert?</h3>

<p><strong>assertAll()</strong> evaluates the collected soft assertion failures and causes the test to fail when one or more validations failed.</p>

<h3>Q9. Can multiple assertions be used in one test method?</h3>

<p>Yes. Multiple assertions can be used when they validate related aspects of the same test scenario.</p>

<h3>Q10. How do you validate a page title?</h3>

<pre><code>Assert.assertEquals(

    driver.getTitle(),

    "Expected Title"

);</code></pre>

<h3>Q11. How do you verify that an element is visible?</h3>

<pre><code>Assert.assertTrue(

    driver.findElement(By.id("login")).isDisplayed()

);</code></pre>

<h3>Q12. What is the difference between wait and assertion?</h3>

<p>A wait synchronizes the test with the application state, while an assertion validates whether the resulting state is correct.</p>

<h3>Q13. How can you add a failure message to an assertion?</h3>

<pre><code>Assert.assertTrue(

    condition,

    "Expected condition was not satisfied"

);</code></pre>

<h3>Q14. When should SoftAssert be used?</h3>

<p>SoftAssert can be useful when multiple independent validations need to be collected before the final test result is evaluated.</p>

<h3>Q15. Can assertions be used with DataProvider?</h3>

<p>Yes. Assertions can validate the expected result for each data set supplied by a DataProvider.</p>

<h3>Q16. Can assertions be used with Page Object Model?</h3>

<p>Yes. Page Object Model can expose page actions and state information, while test methods perform business-level assertions.</p>

<h3>Q17. What happens when a hard assertion fails?</h3>

<p>The current test method stops at the failed assertion and TestNG records the test as failed.</p>

<h3>Q18. What happens when a SoftAssert validation fails?</h3>

<p>The test can continue executing subsequent statements, and the failure is reported when <strong>assertAll()</strong> is called.</p>

<h3>Q19. Should every Selenium action have an assertion?</h3>

<p>Not necessarily. Assertions should validate meaningful expected outcomes rather than being added mechanically after every Selenium action.</p>

<h3>Q20. Why should assertions have meaningful messages?</h3>

<p>Meaningful messages make failed automation tests easier to understand and debug.</p>

<hr>

<h2>68. Best Assertion Practices for Interviews and Projects</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Practice</th><th>Recommendation</th></tr>

<tr><td>Validation</td><td>Always validate important expected outcomes.</td></tr>

<tr><td>Assertion Type</td><td>Choose the assertion that best matches the expected condition.</td></tr>

<tr><td>Hard Assertions</td><td>Use for important checkpoints where continuing is not meaningful.</td></tr>

<tr><td>Soft Assertions</td><td>Use when multiple related validations should be collected.</td></tr>

<tr><td>assertAll()</td><td>Always call it after relevant SoftAssert validations.</td></tr>

<tr><td>Waits</td><td>Synchronize before validating dynamic application states.</td></tr>

<tr><td>Messages</td><td>Use meaningful failure messages where helpful.</td></tr>

<tr><td>POM</td><td>Keep page interactions organized separately from test scenarios.</td></tr>

<tr><td>DataProvider</td><td>Combine assertions with multiple input data sets when appropriate.</td></tr>

<tr><td>Maintainability</td><td>Avoid unnecessary or duplicate assertions.</td></tr>

</table>

<hr>

<h2>69. Quick Revision</h2>

<table border="1" cellpadding="8" cellspacing="0">

<tr><th>Concept</th><th>Remember</th></tr>

<tr><td>Assertion</td><td>Validates actual result against expected behavior.</td></tr>

<tr><td>Assert</td><td>TestNG class used for hard assertions.</td></tr>

<tr><td>assertEquals()</td><td>Checks equality.</td></tr>

<tr><td>assertNotEquals()</td><td>Checks inequality.</td></tr>

<tr><td>assertTrue()</td><td>Checks that a condition is true.</td></tr>

<tr><td>assertFalse()</td><td>Checks that a condition is false.</td></tr>

<tr><td>assertNull()</td><td>Checks that a value is null.</td></tr>

<tr><td>assertNotNull()</td><td>Checks that a value is not null.</td></tr>

<tr><td>assertSame()</td><td>Checks object identity.</td></tr>

<tr><td>assertNotSame()</td><td>Checks different object references.</td></tr>

<tr><td>SoftAssert</td><td>Allows multiple validations to be collected.</td></tr>

<tr><td>assertAll()</td><td>Evaluates collected SoftAssert failures.</td></tr>

<tr><td>Wait</td><td>Synchronizes test execution with application state.</td></tr>

<tr><td>Assertion Message</td><td>Explains the reason for a validation failure.</td></tr>

<tr><td>DataProvider</td><td>Can execute assertions against multiple data sets.</td></tr>

<tr><td>POM</td><td>Separates page actions from test validation logic.</td></tr>

</table>

<hr>

<h2>70. Learning Roadmap</h2>

<pre><code>Core Java

    |

    v

Selenium WebDriver

    |

    v

Locators

    |

    v

WebElements

    |

    v

Browser Interactions

    |

    v

Waits &amp; Synchronization

    |

    v

TestNG

    |

    +-- Test Methods

    +-- Test Annotations

    +-- Assertions

    +-- Test Groups

    +-- Test Dependencies

    +-- DataProvider

    +-- Test Execution

    |

    v

Page Object Model

    |

    v

Automation Framework

    |

    v

Maven

    |

    v

Git &amp; GitHub

    |

    v

Reporting

    |

    v

Jenkins / CI/CD

    |

    v

Parallel Execution

    |

    v

Real-Time Selenium Project</code></pre>

<hr>

<h2>71. Summary</h2>

<p>Assertions are a fundamental part of TestNG-based Selenium automation. Selenium WebDriver performs browser interactions, while TestNG assertions validate whether the application behaves according to the expected requirements.</p>

<p>The most commonly used assertions include <strong>assertEquals(), assertNotEquals(), assertTrue(), assertFalse(), assertNull(), assertNotNull(), assertSame(), and assertNotSame()</strong>. TestNG also provides <strong>SoftAssert</strong> for scenarios where multiple validations need to be collected before the final result is evaluated.</p>

<p>Effective Selenium automation requires more than simply clicking buttons and entering data. A well-designed test should perform the required action, synchronize with the application when necessary, capture the actual result, compare it with the expected result, and use an appropriate assertion to determine the test outcome.</p>

<p>Assertions become even more useful when combined with Selenium WebDriver, Page Object Model, DataProvider, TestNG test methods, waits, reporting, screenshots, Maven, and CI/CD. This combination helps create structured, maintainable, and reliable automation test frameworks.</p>

<hr>

<h2>72. Course Resources</h2>

<p>Learn more about Selenium WebDriver, TestNG, assertions, validations, automation frameworks, data-driven testing, and real-world Selenium projects through the following resources:</p>

<p><a href="https://www.justacademy.co/course-detail/selenium-training" target="_blank" rel="noopener noreferrer">Selenium Training</a></p>

<p><a href="https://www.justacademy.co/register-for-course-demo" target="_blank" rel="noopener noreferrer">Register for Course Demo</a></p>

</div>

Previous Next
whatsapp