assertTrue() in Java: A Complete Tutorial

Faisal Khatri

Posted On: December 12, 2023

view count228638 Views

Read time17 Min Read

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 Assertions 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.

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.

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

parameter 2

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

displayed

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

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.

method

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

actual working

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.

Programming Language/ Tools/Framework Version
Java 17
Selenium WebDriver 4.12.1
JUnit 5 5.10.0
Maven 3.9.4

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.

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

LambdaTest’s Selenium Playground

Checkbox Demo Screen

Checkbox Demo Screen

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

Playground

Redirection Page

Redirection Page

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

Filter Screen

Data List Filter Screen

Data List Filter

Github

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

Info Note

Automate your Java automated tests with Selenium. Try LambdaTest Today!

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

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

createDriver

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

configuration

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.

Chrome browser

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.

Chrome browser is started

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

 test readability

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

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.

 in JUnit 5

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.

allowing

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

checkIfCheckboxOneIsTicked

Filename: CheckboxDemoPage.java

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

CheckboxPage

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.

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.

Modify Run Configuration

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

Security window

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 >

LambdaTest Username

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.

Screenshot of the

Screenshot of the test execution

Screenshot of the test execut

platform name

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.

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

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.

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.

configuration window by

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.

button to close

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

of the test execution

Screenshot of the test execution

checked in the

 LambdaTest Build

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

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.

Apply button

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,

Screenshot of

Screenshot of the test execution

Without assertions

automated test is incomplete

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!

Frequently Asked Questions (FAQs)

What is assertTrue Java?

assertTrue in Java is a method used in testing frameworks like JUnit or TestNG to assert that a given condition is true. It is part of the assertion library and is typically employed to validate expected outcomes during test execution. If the specified condition is false, the test will fail, indicating that the expected result did not occur. This assertion is fundamental in ensuring the correctness of test cases and helps identify issues in the application under test.

What is assertFalse in Java?

The assertFalse method plays a crucial role in testing frameworks such as JUnit or TestNG by allowing developers to verify whether a specific condition is false. It is an integral component of the assertion library and validates anticipated results during the execution of tests. When utilized, if the designated condition is considered true, it triggers a test failure, signifying that the expected outcome has not been achieved. This assertion holds great significance as it ensures the accuracy and reliability of test cases while also aiding in identifying and resolving any potential issues within the tested application.

What is the difference between assertTrue and assertEquals?

assertTrue and assertEquals are both assertion methods commonly used in testing frameworks like JUnit or TestNG, but they serve different purposes. assertTrue is used to verify a boolean condition, ensuring it evaluates to true, while assertEquals is used to compare two values for equality. The choice between them depends on the nature of the test and the specific assertion being made.

Author Profile Author Profile Author Profile

Author’s Profile

Faisal Khatri

Faisal is a Software Testing Professional having 14+ years of experience in automation as well as manual testing. He is a QA, freelancer, blogger and open source contributor. He loves learning new tools and technologies and sharing his experience by writing blogs.

Blogs: 24



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free