assertTrue() in Java: A Complete Tutorial
Tags: asserttrue, javascript, automationtesting
Published: 2024-01-23 08:23:04

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](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage), 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](https://www.lambdatest.com/learning-hub/test-execution?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub) 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](https://www.lambdatest.com/learning-hub/end-to-end-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub) 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](https://www.lambdatest.com/selenium-automation-testing-with-testng?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) 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](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) seamlessly.

In this [JUnit tutorial](https://www.lambdatest.com/learning-hub/junit-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub), we will demonstrate performing assertions and check specific conditions. using the *assertTrue(*) in Java.

***Simplify your data export process with our efficient*** [***SQL to CSV***](https://www.lambdatest.com/free-online-tools/sql-to-csv?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***Converter. Convert SQL queries to CSV format seamlessly and unlock data versatility. Try it now.***

### What are Assertions in test automation?

Assertions are the core concept of [functional testing](https://www.lambdatest.com/learning-hub/functional-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub). 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.

***Looking for an easy way to convert your HTML files to JADE? Try our free online*** [***HTML to JADE***](https://www.lambdatest.com/free-online-tools/html-to-jade?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***converter tool to convert your HTML files to JADE format in seconds.*** 

There are two types of [assertions in automated testing](https://www.lambdatest.com/blog/junit-assertions-example-for-selenium-testing/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=blog):

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

***Tired of manually creating JSON data? Generate*** [***random JSON data***](https://www.lambdatest.com/free-online-tools/random-json-generator?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***in seconds with our easy-to-use tool. Try it now and make your development process a breeze.***

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

{% youtube mkIp_xbbs-w %}

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](https://cdn-images-1.medium.com/max/1200/0*N4_LRylpRfhHLrsx.png)

### 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](https://cdn-images-1.medium.com/max/1200/0*aYSrdi3YYiGM98wc.png)

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.

![image](https://cdn-images-1.medium.com/max/1200/0*zmE2fjce-KRcPW-V.png)

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

![image](https://cdn-images-1.medium.com/max/1200/0*GiqVPd3173nkiTLq.png)

***Need a quick placeholder image for your project? Use our online*** [***placeholder image generator***](https://www.lambdatest.com/free-online-tools/placeholder-image-generator?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***tool that helps you generate customizable images for your projects.***

### 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](https://www.lambdatest.com/selenium-java-testinghttps://www.lambdatest.com/selenium-java-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) at scale on an [online browser farm](https://www.lambdatest.com/online-browser-farm?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) of 3000+ real web browsers and operating systems. You even run your automated test suites with [Selenium](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) in parallel and achieve faster software release cycles.

{% youtube SqQ8SugRDos %}

Subscribe to the [LambdaTest YouTube Channel](https://www.youtube.com/c/LambdaTest?sub_confirmation=1) and stay updated with the latest tutorials around [automated testing](https://www.lambdatest.com/learning-hub/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub), [Selenium testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage), [Java automation testing](https://www.lambdatest.com/java-automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage), and more.

![image](https://cdn-images-1.medium.com/max/1200/1*lopUiII-GM6oAQMKiBwliQ.png)

First, let’s create a Maven project and add the dependencies for [Selenium WebDriver](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub) and JUnit 5 in the *pom.xml* file to set up the project.

```plaintext
<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>
```

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

***Want to generate random binary numbers? Our free online*** [***Random Binary Number Generator***](https://www.lambdatest.com/free-online-tools/random-binary-generator?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***lets you generate random binary numbers quickly and easily. Try it now.***

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

![image](https://cdn-images-1.medium.com/max/1200/1*Uzb0_Pcfixp2E9Ke3JJ-nQ.png)

***LambdaTest’s Selenium Playground***

![image](https://cdn-images-1.medium.com/max/1200/0*AHq4jwaZicODnEVl.png)

***Checkbox Demo Screen***

![image](https://cdn-images-1.medium.com/max/1200/0*esbzXpOOuEPpvyoF.png)

**Test Scenario 2**

1. Open the [LambdaTest’s Selenium Playground](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) website.
    
2. Navigate to the [Redirection](https://www.lambdatest.com/selenium-playground/redirection?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) page.
    
3. *Using assertTrue()*, verify that the page header is displayed on successfully loading the Redirection Page.
    

***LambdaTest’s Selenium Playground***

![image](https://cdn-images-1.medium.com/max/1200/0*60u5dBGfAb9tw53V.png)

***Redirection Page***

![image](https://cdn-images-1.medium.com/max/1200/0*_XEMORvYvyhPMoFa.png)

**Test Scenario 3**

1. Open the [LambdaTest’s Selenium Playground](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) website.
    
2. Navigate to the [Data List Filter](https://www.lambdatest.com/selenium-playground/redirection?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) 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](https://cdn-images-1.medium.com/max/1200/0*SJLostgLvQ0cxndk.png)

***Data List Filter Screen***

![image](https://cdn-images-1.medium.com/max/1200/0*zr5aeWzF3jb-yZmu.png)

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

***Need random dates? Our online*** [***Random Date Generator***](https://www.lambdatest.com/free-online-tools/random-date-generator?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***tool generates random dates for your projects. Choose a start and end date, and let our tool do the rest.***

### Implementation \[Test Scenario 1\]

In test scenario 1, we must open [LambdaTest’s Selenium Playground](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) website and navigate to the [Checkbox Demo](https://www.lambdatest.com/selenium-playground/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](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/test/java/io/github/mfaisalkhatri/tests/seleniumautomationtests/SeleniumPlaygroundTests.java)

```plaintext
 @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());
    }
```

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](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/main/java/io/github/mfaisalkhatri/drivers/DriverManager.java)

![image](https://cdn-images-1.medium.com/max/1200/0*VN3-jmrK1BAhS1Ic.png)

The browser’s name passed in the *createDriver()* method parameter will get started. *The REMOTE\_CHROME* browser name will call the *setupChromeInRemote()* method.

![image](https://cdn-images-1.medium.com/max/1200/0*pRNYUlWImCcKRrYb.png)

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](https://www.lambdatest.com/capabilities-generator/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage).

![image](https://cdn-images-1.medium.com/max/1200/0*0NNwbG7EcIcj8j00.png)

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](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) website.

![image](https://cdn-images-1.medium.com/max/1200/0*8lLW_MrWaf3xSeto.png)

On the website’s Homepage, the [*Checkbox Demo*](https://www.lambdatest.com/selenium-playground/checkbox-demo?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) link will be clicked to navigate the user to the *Checkbox Demo* page.

![image](https://cdn-images-1.medium.com/max/1200/0*r8otgyUX0vB_iLTN.png)

The [Page Object Model](https://www.lambdatest.com/blog/selenium-java-testing-page-object-model/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=blog) 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.

***Our*** [***HTML Minify***](https://www.lambdatest.com/free-online-tools/html-minify?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***is a perfect tool for anyone looking to optimize website’s speed. Minify your code and optimize website for faster loading times in few seconds.***

**Filename:** [HomePage.java](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/test/java/io/github/mfaisalkhatri/seleniumplayground/pages/HomePage.java)

```plaintext
public class HomePage {

    public void navigateToLink (final String linkText) {
        getDriver ().findElement (By.linkText (linkText)).click ();
    }
}
```

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](https://cdn-images-1.medium.com/max/1200/0*PaChkjAWZkfaOTOl.png)

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](https://www.lambdatest.com/learning-hub/css-selectors?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=learning_hub) are faster and simpler than [XPath](https://www.lambdatest.com/blog/complete-guide-for-using-xpath-in-selenium-with-examples/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=blog), allowing for a clearer method to locate web elements. We can use the CSS Selector *“div:nth-child(2) &gt; div:nth-child(1) &gt; input\[type=”checkbox”\]”* to locate the Option 1 checkbox.

![image](https://cdn-images-1.medium.com/max/1200/0*I_tTJwfidYosbDt4.png)

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

![image](https://cdn-images-1.medium.com/max/1200/0*Rvtbg1Mm294ejVLJ.png)

**Filename:** [CheckboxDemoPage.java](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/test/java/io/github/mfaisalkhatri/seleniumplayground/pages/CheckboxDemoPage.java)

```plaintext
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();
    }
}
```

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

![image](https://cdn-images-1.medium.com/max/1200/0*2Z0CtCGNTUZKrU-m.png)

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

***Need to convert hex to decimal? Our online*** [***Hex to Decimal***](https://www.lambdatest.com/free-online-tools/hex-to-decimal?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***Converter tool converts hexadecimal to decimal numbers quickly. Get your conversions done in no time.***

**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](https://cdn-images-1.medium.com/max/1200/0*vLMQ7IIj90sUMGES.png)

The LambdaTest Username and Access Key values can be copied from the *Profile &gt;&gt; Account Settings &gt;&gt; Password and Security window*.

![image](https://cdn-images-1.medium.com/max/1200/0*5t-ysz6zsOSS-iKJ.png)

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

*\-DLT\_USERNAME= &lt; LambdaTest Username &gt; -DLT\_ACCESS\_KEY=&lt; LambdaTest\_Access\_Key &gt;*

![image](https://cdn-images-1.medium.com/max/1200/0*WOmIzGYpGm-LXEhL.png)

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](https://cdn-images-1.medium.com/max/1200/0*amlBWAzorm-8XFQg.png)

***Screenshot of the test execution***

![image](https://cdn-images-1.medium.com/max/1200/0*JKj4F1fxDDTPr6Yu.png)

![image](https://cdn-images-1.medium.com/max/1200/0*at6jYXkHVNnkb5Hb.png)

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.

***Struggling with messy Lua scripts? Our*** [***Lua Beautifier***](https://www.lambdatest.com/free-online-tools/lua-beautifier?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***tool provides clean and structured formatting. Beautify your code and Improve readability today.***

### Implementation \[Test Scenario 2\]

In test scenario 2, we will navigate to the [Redirection](https://www.lambdatest.com/selenium-playground/redirection?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) page on [LambdaTest’s Selenium Playground](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) 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](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/test/java/io/github/mfaisalkhatri/tests/seleniumautomationtests/SeleniumPlaygroundTests.java)

```plaintext
 @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());
    }
```

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.

```plaintext
public class RedirectionPage {

    public boolean isPageTitleDisplayed() {
        return getDriver().findElement(By.tagName("h1")).isDisplayed();
    }
}
```

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.

***Struggling with messy*** [***Python Formatter & Beautifier***](https://www.lambdatest.com/free-online-tools/python-beautifier?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***Online scripts? Our Python Formatter & Beautifier Online tool provides clean and structured formatting. Beautify your code and Improve readability today.*** 

**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](https://cdn-images-1.medium.com/max/1200/0*1hP4etd-glsG7Z4x.png)

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](https://cdn-images-1.medium.com/max/1200/0*YUjjgzaO7ecwYS_N.png)

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

![image](https://cdn-images-1.medium.com/max/1200/0*EetKGE7UV9kWSGVx.png)

***Screenshot of the test execution***

![image](https://cdn-images-1.medium.com/max/1200/0*xak0JPeg04kbqE3V.png)

![image](https://cdn-images-1.medium.com/max/1200/0*fnzBxPYgxFEshITF.png)

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.

***Don’t let encoding IDNs slow you down. Save time and hassle with our*** [***IDN Encode***](https://www.lambdatest.com/free-online-tools/idn-encode?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***free online tool to quickly and easily converts internationalized domain names. Try it now.***

### Implementation \[Test Scenario 3\]

In test scenario 3, we will navigate to the [Data Filter List](https://www.lambdatest.com/selenium-playground/data-list-filter-demo?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) page on [LambdaTest’s Selenium playground](https://www.lambdatest.com/selenium-playground/?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=webpage) 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](https://github.com/mfaisalkhatri/junit-examples/blob/main/src/test/java/io/github/mfaisalkhatri/tests/seleniumautomationtests/SeleniumPlaygroundTests.java)

```plaintext
 @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));
    }
```

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](https://cdn-images-1.medium.com/max/1200/0*y2_brq6iboHlzO8V.png)

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](https://cdn-images-1.medium.com/max/1200/0*eBQ_MVH1K2keBzq8.png)

***Screenshot of the test execution***

![image](https://cdn-images-1.medium.com/max/1200/0*_mJbbmbthC_mr8h-.png)

![image](https://cdn-images-1.medium.com/max/1200/0*wm-m6dt9nLKCHpvO.png)

***Simplify the process of converting*** [***JSON to YAML***](https://www.lambdatest.com/free-online-tools/json-to-yaml?utm_source=devto&utm_medium=organic&utm_campaign=jan_22&utm_term=ap&utm_content=free_online_tools) ***with our online JSON to YAML converter tool to convert JSON files to YAML. No sign-up required. Get started now.***

### 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!