DEV Community

Cover image for assertTrue() in Java: A Complete Tutorial
Faisalkhatri123 for LambdaTest

Posted on • Originally published at lambdatest.com

assertTrue() in Java: A Complete Tutorial

Assertions are an important part of the automation testing process, ensuring the software functions as anticipated. If it is not working as desired, the tests have to be marked as failure and need to be halted to make the necessary investigation for the failure.

An assertion statement helps to test the assumption about the test. When performing test automation, assertions help us automatically verify the tests’ output. In Selenium automation testing, we come across multiple scenarios where it is necessary to decide on the subsequent execution of the tests.

This is important in cases where the test result of the previous test execution is a failure. If the tests depend on each other, it is recommended to halt the execution at the exact failure step by using *Hard Assertion*s so the other dependent tests are skipped to save time.

Consider an example of an end-to-end testing journey of an eCommerce application where the product checkout from cart tests depends on the add product to cart tests. If the add product to cart tests fail, subsequent tests should not be executed as they will fail.

The test execution halts when the condition (part of the assertion) is unmet. Hence, when Selenium automation testing with TestNG is performed, assertions can help us understand the expected behavior of the application and allow us to check the quality of the software under test.

JUnit 5 is one of the popular testing frameworks used by many test automation projects to execute and run automation tests and perform assertions. It is a very good library with different functions to perform automation testing seamlessly.

In this JUnit tutorial, we will demonstrate performing assertions and check specific conditions. using the assertTrue() in Java.

Get your CSS validated by our CSS Validator and eliminate syntax errors and other issues that could affect your website’s performance. Ensure your CSS code is error-free today. 

What are Assertions in test automation?

Assertions are the core concept of functional testing. In automated testing, it forms an integral part of the test and is used to derive the outcome of the test execution. The test passes if the test result confirms the assertion; otherwise, it will fail.

It brings many benefits to test automation, like providing accurate test results, speeding up the test process by performing the required checks automatically, and confirming the expected behavior of the software under test. It also helps you catch the bugs and errors in the software easily, thus aiding you in getting faster feedback on the builds.

Assertions are Boolean expressions confirming where the specified condition works and are considered passed per the application’s behavior. If the outcome condition is true, the test will pass; if the outcome is false, the test will fail.

Consider an example of a Login web page, where the test is to check the login functions properly. Here, we make an assertion condition that if the Logout button is displayed successfully after Login, the test is marked as passed. If the Logout button is not displayed after Login, the assertion will fail, marking the test as a failure.

There are two types of assertions in automated testing:

  • Hard Assertion

  • Soft Assertion

Hard Assertion

Hard assertions ensure that the test execution is stopped when the asserting condition is not met. The next steps or tests, if any, will only proceed if the asserting condition is evaluated to be true.

This helps in the automated pipeline as it turns red in case of test failures, and test execution is halted until the necessary fixes are made to the build.

Don’t let CSV errors slow you down. Validate and lint your CSV data with ease using our free online CSV Validator tool. Get accurate and error-free results in seconds.

Soft Assertion

With Soft assertions, the test execution is not stopped if the asserting condition is not met. Even after the assertion fails, the test execution will continue until it reaches the test’s end. After the tests are executed, all the respective failures will be displayed in the logs.

Soft assertions should be used when the tests are not dependent on each other and passing one test condition does not impact the upcoming tests.

Having learned about the two types of assertions, Let us quickly move towards learning the assertTrue() in Java for performing assertions in the automated tests.

What is the assertTrue() in Java?

assertTrue() method is available in the “org.junit.Assertions” class in JUnit 5. The Assertions class in JUnit 5 is a collection of utility methods supporting asserting test conditions.

It verifies the supplied condition and checks if it is True. Following are the two overloaded assertTrue() methods provided by JUnit 5:

assertTrue(boolean condition)

In this method, the Boolean condition is supplied as a parameter. If the condition is true, the test passes or is marked as a failure.

Syntax

image

assertTrue(boolean condition, String message)

In this method, the Boolean condition is supplied as the first parameter, and the second parameter is the message text displayed in case the condition fails.

Syntax

image

In the next section, let’s learn how to use these methods in the test.

Minify your JS code without changing its functionality with our easy-to-use JavaScript Minifier that reduces the size of your scripts and improve website speed.

How to use the assertTrue() method in the test?

There are two ways to use the assertTrue() method in the test.

The first is using the Assertions class and then calling the assertTrue() in Java.

Image

The second way is to directly import the static assertTrue() method in the test.

Image

Setting up the project

Let’s now delve into the test scenarios and check the actual working of the assertTrue() in Java. We will use the following tech stack to demonstrate and run the tests on the LambdaTest cloud grid.

LambdaTest is an AI-powered test orchestration and execution platform that lets you perform Selenium Java testing at scale on an online browser farm of 3000+ real web browsers and operating systems. You even run your automated test suites with Selenium in parallel and achieve faster software release cycles.

Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated testing, Selenium testing, Java automation testing, and more.

image

First, let’s create a Maven project and add the dependencies for Selenium WebDriver and JUnit 5 in the pom.xml file to set up the project.

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.github.mfaisalkhatri</groupId>
    <artifactId>junit-examples</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>junit-examples</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <junit.version>5.10.0</junit.version>
        <selenium.version>4.12.1</selenium.version>
        <junit.platform.launcher.version>1.10.0</junit.platform.launcher.version>
<maven-surefire-plugin.version>3.1.2</maven-surefire-plugin.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform-launcher -->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>${junit.platform.launcher.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <includes>**/*Test*.java</includes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Enter fullscreen mode Exit fullscreen mode

The project setup is complete, with the dependencies updated in the pom.xml, and we can now proceed to write the automated tests.

Test Scenarios

We will cover the following test scenarios as a part of the automation test to demo the working of the assertTrue() in Java.

Test Scenario 1

  1. Open the LambdaTest’s Selenium Playground website.

  2. Navigate to the Checkbox Demo screen.

  3. In the Disabled Checkbox Demo section, tick Option 1.

  4. Using assertTrue(), verify that the Option 1 checkbox is ticked successfully.

  5. Next, using assertTrue(), verify that the Option 3 checkbox is disabled.

LambdaTest’s Selenium Playground

image

Checkbox Demo Screen

image

Test Scenario 2

  1. Open the LambdaTest’s Selenium Playground website.

  2. Navigate to the Redirection page.

  3. Using assertTrue(), verify that the page header is displayed on successfully loading the Redirection Page.

LambdaTest’s Selenium Playground

image

Redirection Page

image

Test Scenario 3

  1. Open the LambdaTest’s Selenium Playground website.

  2. Navigate to the Data List Filter page.

  3. Search for a record by entering the Attendee name.

  4. Using assertTrue(), verify that the data retrieved contains the Attendee name entered in the search box.

LambdaTest’s Selenium Playground

image

Data List Filter Screen

image

We will run the tests on the Chrome browser on the Windows 10 platform using the LambdaTest Cloud grid.

Transform your messy CSS code into beautiful and organized code with our user-friendly and efficient online free CSS Prettifier tool with just a few clicks.

Implementation [Test Scenario 1]

In test scenario 1, we must open LambdaTest’s Selenium Playground website and navigate to the Checkbox Demo screen. We need to tick the Option 1 checkbox in the Disabled Checkbox Demo section and use the assertTrue() in Java to verify that it is ticked successfully. We will also check that the Option 3 checkbox is disabled using the assertTrue() method.

The following automated test method named checkboxDemoTest() is written in the SeleniumPlaygroundTests class that will help us achieve the automation of the test scenario:

Filename: SeleniumPlaygroundTests.java

 @Test
    public void checkboxDemoTest() {
        createDriver(Browsers.REMOTE_CHROME);
        final String website = "https://www.lambdatest.com/selenium-playground/";
        getDriver().get(website);

        final HomePage homePage = new HomePage();
        homePage.navigateToLink("Checkbox Demo");

        final var checkboxDemoPage = new CheckboxDemoPage();
        assertTrue(checkboxDemoPage.checkIfCheckboxOneIsTicked(), "Check box one is not ticked");
        assertTrue(checkboxDemoPage.checkIfCheckboxThreeIsDisabled());
    }
Enter fullscreen mode Exit fullscreen mode

The first line of the method will create an instance of the Chrome browser in the LambdaTest Cloud grid. createDriver() method is a static method in the DriverManager class that will help us instantiate a new instance of WebDriver.

Filename: DriverManager.java

Image

The browser’s name passed in the createDriver() method parameter will get started. The REMOTE_CHROME browser name will call the setupChromeInRemote() method.

Image

This method will set all the desired capabilities and the configuration required for running the tests on the LambdaTest Cloud grid. These capabilities can be directly copied using the LambdaTest Capabilities Generator.

Image

Once the driver session is created and the Chrome browser is started, the next line in the test will navigate the user to the LambdaTest Selenium Playground website.

Image

On the website’s Homepage, the Checkbox Demo link will be clicked to navigate the user to the Checkbox Demo page.

Image

The Page Object Model is used in this project as it helps test readability, reduces code duplication, and acts as an interface for the web page under test. The HomePage class houses the page objects for the Home Page of LambdaTest’s Selenium Playground website.

As the Homepage contains links to different website windows, a generic method has been created to search the links using the respective LinkText and then click on it to navigate to the required page.

Filename: HomePage.java

public class HomePage {

    public void navigateToLink (final String linkText) {
        getDriver ().findElement (By.linkText (linkText)).click ();
    }
}
Enter fullscreen mode Exit fullscreen mode

The next step is to tick the Option 1 checkbox under the Disabled Checkbox Demo section and verify that it is ticked successfully using the assertTrue() in Java.

image

We will also provide a message in the assertTrue() method so that if the test fails, this text will be printed in the console for easy interpretation of the failure.

The page objects for the Checkbox page are updated in the CheckboxDemoPage class. The checkboxOne() method will return a WebElement for the Option 1 checkbox.

CSS Selectors are faster and simpler than XPath, allowing for a clearer method to locate web elements. We can use the CSS Selector “div:nth-child(2) > div:nth-child(1) > input[type=”checkbox”]” to locate the Option 1 checkbox.

image

The checkIfCheckboxOneIsTicked() method will tick the Option 1 checkbox and return the boolean value stating if the checkbox is selected.

image

Filename: CheckboxDemoPage.java

public class CheckboxDemoPage {

    public WebElement checkboxOne() {
        return getDriver().findElement(By.cssSelector("div:nth-child(2) > div:nth-child(1) > input[type=\"checkbox\"]"));
    }
    public WebElement checkboxThree() {
        return getDriver().findElement(By.cssSelector("div:nth-child(2) > div:nth-child(3) > input[type=\"checkbox\"]"));
    }

    public void tickCheckBoxOne () {
        checkboxOne().click();
    }

    public boolean checkIfCheckboxOneIsTicked() {
       tickCheckBoxOne();
        return this.checkboxOne().isSelected();
    }

    public boolean checkIfCheckboxThreeIsDisabled() {
        return !this.checkboxThree().isEnabled();
    }
}
Enter fullscreen mode Exit fullscreen mode

The next assertion performed using the assertTrue() in Java is to check that the Option 3 checkbox is disabled.

image

The checkIfCheckboxThreeIsDisabled() method from the CheckboxPage class is used to check the disabled state of the checkbox.

The point to note here is that we are using the “!” while returning the output of the boolean condition from the checkIfCheckboxThreeIsDisabled() method that uses the isEnabled() method. So, ideally, it will check that the checkbox is disabled and return the output as true, else it will return false.

Get faster loading times and better user experience with our efficient JSON minify tool. Quickly compress your JSON data with ease and optimize your website now.

Test Execution

The LambdaTest Username and Access Key must be provided for authentication to run tests successfully on the LambdaTest Cloud grid. These values can be updated in the Run Configuration window, which can be opened using the Modify Run Configuration option by clicking the Green Play button beside the test method name.

image

The LambdaTest Username and Access Key values can be copied from the Profile >> Account Settings >> Password and Security window.

image

In the Run Configuration window, update the values for the Username and Access Key as follows :

-DLT_USERNAME= < LambdaTest Username > -DLT_ACCESS_KEY=< LambdaTest_Access_Key >

image

Once the credentials are successfully updated in the configuration window, the tests can be executed by selecting Run Configuration from the dropdown in the top menu bar and clicking on the green button.

Image

Screenshot of the test execution

Image

image

All the test details can be viewed on the LambdaTest dashboard, including platform name, browser name, resolution, test execution logs, time taken to execute the tests, etc.

Don’t waste time debugging your YAML files. Use our free YAML validator tool to validate your YAML code quickly and identify syntax errors and fix them.

Implementation [Test Scenario 2]

In test scenario 2, we will navigate to the Redirection page on LambdaTest’s Selenium Playground website and verify that the page title is displayed using the assertTrue() in Java.

The steps for test scenario 2 will be automated using the redirectionPageTest() method created inside the SeleniumPlaygroundTests.java class.

Filename: SeleniumPlaygroundTests.java

 @Test
    public void redirectionPageTest() {
        createDriver(Browsers.REMOTE_CHROME);
        final String website = "https://www.lambdatest.com/selenium-playground/";
        getDriver().get(website);

        final HomePage homePage = new HomePage();
        homePage.navigateToLink("Redirection");

        final var redirectionPage = new RedirectionPage();
        assertTrue(redirectionPage.isPageTitleDisplayed());
    }
Enter fullscreen mode Exit fullscreen mode

The initial 3 lines in the test are the same as we discussed in the test scenario 1 implementation. We will not discuss the configuration and setup for creating a WebDriver session and launching the Chrome browser.

Once the website is loaded on the browser, the Redirection page is navigated, and further interaction is taken to check that the title is displayed on the page.

public class RedirectionPage {

    public boolean isPageTitleDisplayed() {
        return getDriver().findElement(By.tagName("h1")).isDisplayed();
    }
}
Enter fullscreen mode Exit fullscreen mode

The RedirectionPage class is created to update all the page objects related to the Redirection page. The isPageTitleDisplayed() method returns a boolean value using the Selenium WebDriver’s isDisplayed() method.

First, the Page title will be located, and then, using the isDisplayed() method, the verification will be done to check that it is displayed on the page. The assertTrue() method is finally used in the test to check the result of the boolean condition returned by the isPageTitleDisplayed() method.

Test Execution

The steps followed while executing Test Scenario 1 for setting the LambdaTest Username and AccessKey to execute the tests on the LambdaTest Cloud grid. The same steps need to be followed while executing this test.

As we have already set the LambdaTest Username and AccessKey in the Configuration window, we can re-use the same window and just change the test method name to run this test.

Click the Run/Debug Configuration dropdown and select the Edit Configuration option.

image

Select the redirectionPageTest() method name in the configuration window by clicking on the three dots next to the Method name field. Leave the other settings/configurations as they are and click “Apply” and then the “OK” button to close the configuration window.

Image

The tests can now be executed by clicking on the green button next to the Run/Debug configuration field.

Image

Screenshot of the test execution

Image

Image

The test execution can be checked in the LambdaTest Build details windows after logging in to the LambdaTest website. This window provides granular details of the test execution that help know the test analytics and execution status.

Implementation [Test Scenario 3]

In test scenario 3, we will navigate to the Data Filter List page on LambdaTest’s Selenium playground website to search for an attendee record by entering a name. Once the records are retrieved based on the filter according to the name provided, the record will be verified using the assertTrue() method by checking if the Attendee name in the record contains the name searched for.

The steps for test scenario 3 will be automated using the dataFilterPageTest() method that is updated inside the SeleniumPlaygroundTests.java class.

Filename: SeleniumPlaygroundTests.java

 @Test
    public void dataFilterPageTest() {
        createDriver(Browsers.REMOTE_CHROME);
        final String website = "https://www.lambdatest.com/selenium-playground/";
        getDriver().get(website);

        final HomePage homePage = new HomePage();
        homePage.navigateToLink("Data List Filter");

        final var dataListFilterPage = new DataListFilterPage();
        final String attendeeName = "Dwayne";
        dataListFilterPage.searchAttendees(attendeeName);
        assertTrue(dataListFilterPage.getAttendeeName().contains(attendeeName));
    }
Enter fullscreen mode Exit fullscreen mode

In this test, we will first open the Chrome browser in the LambdaTest Cloud grid and navigate to the Data List Filter Page on LambdaTest’s Selenium Playground website.

Next, it will search for the data with the attendee name “Dwayne”. Once the data is loaded on the page, the assertTrue() method will check the condition that the attendee name in the results contains the text — “Dwayne”. The test will be marked as pass if the text is found in the Attendee’s name in the data results.

Test Execution

The test for scenario 3 can be easily run by just changing the method name from the Run Configuration window, as shown in the screenshot below.

Image

Once the method is selected, click the Apply button and then the OK button to close the config window. To run the test, click the Green Play button on the toolbar on the top,

Image

Screenshot of the test execution

Image

Image

Conclusion

Without assertions, an automated test is incomplete. Assertions help us to derive the results of the automated tests. This can help in providing faster feedback on the software builds.

assertTrue() in Java is used to perform assertions in automated tests. We can verify a boolean condition using this method. This web automation method can ideally be used to check if a particular web element, like a checkbox or a radio button is enabled. It can also help in checking if a particular text is displayed. Further, it can be used for checking boolean conditions like text on a web page containing a particular string or text.

I hope this helps you in writing better assertions for the automated tests.

Happy Testing!

Top comments (0)