AssertJ in Selenium Java testing

AssertJ in Selenium Java testing

AssertJ is a powerful assertion library for Java, designed to make your tests more readable, maintainable, and expressive. It provides a fluent API that allows you to write assertions in a natural language style, making it easier to understand what your tests are checking. In this blog, we'll explore what AssertJ is, why it's beneficial, and how you can leverage it in Selenium Java testing to write more robust and effective automated tests.

What is AssertJ?

AssertJ is a Java library that provides a rich set of assertion methods to perform various checks in your code. Unlike traditional assertion libraries like JUnit's built-in assertions, AssertJ offers a more fluent and intuitive API, allowing you to chain assertions together in a natural and readable way.

One of the key features of AssertJ is its extensive support for different types of objects and data structures. Whether you're dealing with simple types like strings and numbers or complex data structures like collections and maps, AssertJ provides specialized assertions tailored to each data type, making it easier to write precise and meaningful tests.

Why use AssertJ?

1. Readability: AssertJ's fluent API allows you to write assertions in a more natural language style, making your tests easier to read and understand. This can be especially beneficial when working in teams where multiple developers need to collaborate on writing and maintaining tests.

2. Expressiveness: With AssertJ, you can express your test assertions more clearly and concisely, improving the clarity and intent of your tests. This can help you identify and diagnose issues more quickly, reducing the time spent debugging failing tests.

3. Comprehensive Assertions: AssertJ provides a wide range of assertion methods covering different data types and scenarios. Whether you need to check the value of a single variable or validate the contents of a complex data structure, AssertJ has you covered with its extensive set of assertion methods.

4. Error Messages: AssertJ generates informative error messages when assertions fail, helping you pinpoint the exact cause of the failure quickly. This can streamline the debugging process and make it easier to fix failing tests.

How to use AssertJ in Selenium Java testing

Now that we've covered the basics of AssertJ, let's see how we can integrate it into Selenium Java testing to write more effective automated tests.

1. Setup AssertJ: Start by adding AssertJ as a dependency to your Maven or Gradle project. You can do this by including the AssertJ artifacts in your project's pom.xml or build.gradle file.

<!-- https://mvnrepository.com/artifact/org.assertj/assertj-core -->

        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.25.3</version>
            <scope>test</scope>
        </dependency>        

2. Write Assertions: Once AssertJ is set up, you can start writing assertions in your Selenium tests using AssertJ's fluent API. For example, if you want to verify the text of a web element, you can use the isEqualTo assertion:

import static org.assertj.core.api.Assertions.assertThat;

WebElement element = driver.findElement(By.id("elementId"));
assertThat(element.getText()).isEqualTo("Expected Text");
        

Iterable/Array Assertions:-

List<String> list = Arrays.asList("1", "2", "3");
assertThat(list).contains("1");

assertThat(list).isNotEmpty();

assertThat(list).startsWith("1");        

3. Chaining Assertions: AssertJ allows you to chain multiple assertions together, making it easy to perform complex checks in a single statement. For example, you can verify the presence of an element and its text simultaneously:

assertThat(driver.findElement(By.id("elementId")))
    .isNotNull()
    .hasText("Expected Text");

        


assertThat(frodo)
  .isNotEqualTo(sauron)
  .isIn(fellowshipOfTheRing);

assertThat(frodo.getName())
  .startsWith("Fro")
  .endsWith("do")
  .isEqualToIgnoringCase("frodo");

assertThat(fellowshipOfTheRing)
  .hasSize(9)
  .contains(frodo, sam)
  .doesNotContain(sauron);
        
File Assertions:-

 assertThat(someFile)
   .exists()
   .isFile()
   .canRead()
   .canWrite();        

4. Handling Errors: When an assertion fails, AssertJ provides detailed error messages that describe the expected and actual values, making it easier to diagnose and fix the issue. This can be invaluable when troubleshooting failing Selenium tests.

5. Describing Assertions: In order to achieve even higher verbosity level, you can create dynamically generated custom descriptions for your assertions. The key to doing this is the as(String description, Object… args) method.

Describing Assertions:- 

If you define your assertion like this:

assertThat(person.getAge())
  .as("%s's age should be equal to 100", person.getName())
  .isEqualTo(100);


this is what you will get when running tests:

[Alex's age should be equal to 100] expected:<100> but was:<34>        

Example of Selenium Java Test with AssertJ Library:

package com.seleniumsessions;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static org.assertj.core.api.Assertions.*;

import java.time.Duration;

public class AssertJTesting {
    public static WebDriver driver;

    @BeforeClass
    public void setup()
    {
        driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(25));
        driver.manage().window().maximize();
    }
    @AfterClass
    public void tearDown()
    {
        driver.quit();
    }

    @Test
    public void animationButtonClickTest() {
        // Navigate to the webpage
        driver.get("https://naveenautomationlabs.com/opencart/");
        WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(15));
        WebElement menu_text = wait
                .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("https://a[normalize-space()='Desktops']")));
        String text = menu_text.getText();
        assertThat(text).as("Verify text of Menu link").isEqualToIgnoringCase("Desktops");

    }
}
        

If Test is failed then you will see output as :

java.lang.AssertionError: [Verify text of Menu link] 
expected: "Desktopsk"
 but was: "Desktops"
ignoring case considerations        

By leveraging AssertJ in your Selenium Java testing, you can write more expressive, readable, and robust automated tests that help ensure the quality and reliability of your web applications.

In conclusion, AssertJ is a valuable tool for writing effective assertions in Java tests, including Selenium tests. Its fluent API, comprehensive assertion methods, and informative error messages make it an excellent choice for improving the readability, expressiveness, and reliability of your automated tests. By incorporating AssertJ into your testing workflow, you can streamline the testing process, identify issues more quickly, and ultimately deliver higher-quality software.

Happy Testing!



要查看或添加评论,请登录

社区洞察

其他会员也浏览了