Assertion Using AssertJ

QEKafe
3 min readOct 31, 2020

Hi Folks,
Hope you are all doing good and are safe in these testing times. As an effort to connect with you guys we are trying to come up with topics relevant to our community fellows. We started with our series on Assertions and in continuation to that, we bring AssertJ as a focus today.

So let’s get going!

What is AssertJ?

AssertJ provides a rich set of assertions, truly helpful error messages, improves test code readability, and is designed to be super easy to use within your favorite IDE.
AssertJ is a library for simplifying the writing of assert statements in tests. It also improves the readability of asserts statements. It has a fluent interface for assertions, which makes it easy for your code completion to help you write them. The base method for AssertJ assertions is the assertThat method followed by the assertion.

Getting Started with AssertJ

AssertJ artifacts are in the Maven central repository.

<dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <!-- use 2.9.1 for Java 7 projects --> <version>3.11.1</version> <scope>test</scope> </dependency>

For Gradle,

testCompile("org.assertj:assertj-core:3.11.1")

To start, import all rules using

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

Assertions in AssertJ

Assertions in AssertJ are written using Assertions.assertThat() followed by the actual assertion/ condition. Let’s try to see how to write a basic assertion.

import static org.assertj.core.api.Assertions.assertThat; 
public class AssertionsExample {
@Test void sampleAssertion() {
assertThat("This is my sample Test").isNotNull().startsWith("This") .contains("sample") .endsWith("Test");
}
}

Supported Object Type — AssertJ supports assertions for an extensive list of object types. Here are a few of them.

A detailed list of objects type can be found at https://assertj.github.io/doc/#assertj-core-supported-types

Assertion Descriptions — Assertions without any descriptions can sometimes be confusing as they keep the developer/tester guessing about what the assertion is written for. Using AssertJ, we can describe a failing assertion. The thing to keep in mind here is that “as” should be called before assertion or else it will be ignored.

assertThat(product.getPrice()).as("check %s's price", product.getName()).isEqualTo(100);

Overriding Error Message — Although AssertJ provides a descriptive message on failures, sometimes we need to provide a more helpful message as per our business needs. This can be easily done using withFailMessage()

assertThat(product.getPrice()).withFailMessage("price mismatch for %s", product.getName()).isEqualTo(100);

Exception Based Assertions — In this section we talk about how to assert if an exception has occurred and if it is the expected one or not. AssertJ provides multiple ways to handle this.

  • assertThatNullPointerException
  • assertThatIllegalArgumentException
  • assertThatIllegalStateException
  • assertThatIOException
assertThatIOException().isThrownBy(() -> { throw new IOException("boom!"); }).withMessage("%s!", "boom").withMessageContaining("boom").withNoCause();

Soft Assertions using AssertJ — Usually we stop our execution on an assertion failure. But sometimes, we want to collect and capture all of them instead of stopping the execution at first. This is where the Soft Assertions in AssertJ come in handy. This can be implemented as below:

assertAll()

void auto_closeable_soft_assertions_example() { try (AutoCloseableSoftAssertions softly = new AutoCloseableSoftAssertions()) { 
softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien");
softly.assertThat(42).as("response to Everything").isGreaterThan(100); // no need to call assertAll, this is done when softly is closed.softly.assertThat("Gandalf").isEqualTo("Sauron");
}

assertSoftly static method

@Test void assertSoftly_example() {SoftAssertions.assertSoftly(softly -> { softly.assertThat("George Martin").as("great authors").isEqualTo("JRR Tolkien"); softly.assertThat(42).as("response to Everything").isGreaterThan(100); //no need to call assertAll(), assertSoftly does it for us.softly.assertThat("Gandalf").isEqualTo("Sauron"); }); 
}

Hope this helps our community folks who are planning to use AssertJ or are looking for alternate assertion libraries. We are already working on bringing a comparative analysis of various assertion libraries to make the task of choosing one easier for you.

Take care. Thanks for your support.

Originally published at https://www.qekafe.com on October 31, 2020.

--

--

QEKafe

Our aim is to share cutting-edge Trends, Technologies and Best Practices with QE community