Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Introduction to AssertJ

$
0
0

I just released the Starter Class of "Learn Spring Security":

>> CHECK OUT THE COURSE

1. Overview

In this article we will be exploring AssertJ – an opensource community-driven library used for writing fluent and rich assertions in Java tests.

This article focuses on tools available in the basic AssertJ module called AssertJ-core.

2. Maven Dependencies

In order to use AssertJ, you need to include the following section in your pom.xml file:

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

This dependency covers only the basic Java assertions. If you want to use advanced assertions, you will need to add additional modules separately.

Note that for Java 7 and earlier you should use AssertJ core version 2.x.x.

Latest versions can be found here.

3. Introduction

AssertJ provides a set of classes and utility methods that allow us to write fluent and beautiful assertions easily for:

  • Standard Java
  • Java 8
  • Guava
  • Joda Time
  • Neo4J and
  • Swing components

A detailed list of all modules is available on project’s website.

Let’s start with a few examples, right from the AssertJ’s documentation:

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

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

assertThat(fellowshipOfTheRing)
  .hasSize(9)
  .contains(frodo, sam)
  .doesNotContain(sauron);

The above examples are only the tip of the iceberg, but gives us an overview of how writing assertions with this library might look like.

 4. AssertJ in Action

In this section we’ll focus on setting up AssertJ and exploring its possibilities.

4.1. Getting Started

With the jar of the library on a classpath, enabling assertions is as easy as adding a single static import to your test class:

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

4.2. Writing Assertions

In order to write an assertion, you always need to start by passing your object to the Assertions.assertThat() method and then you follow with the actual assertions.

It’s important to remember that unlike some other libraries, the code below does not actually assert anything yet and will never fail a test:

assertThat(anyRefenceOrValue);

If you leverage your IDE’s code completion features, writing AssertJ assertions becomes incredibly easy due to its very descriptive methods. This is how it looks like in IntelliJ IDEA 16:

IDE's code completion features

IDE’s code completion features

 

As you can see, you have dozens of contextual methods to choose from and those are available only for String type. Let’s explore in detail some of this API and look at some specific assertions.

4.3. Object Assertions

Objects can be compared in various ways either to determine equality of two objects or to examine the fields of an object.

Let’s look at two ways that we can compare the equality of two objects. Given the following two Dog objects fido and fidosClone:

public class Dog { 
    private String name; 
    private Float weight;
    
    // standard getters and setters
}

Dog fido = new Dog("Fido", 5.25);

Dog fidosClone = new Dog("Fido", 5.25);

We can compare equality with the following assertion:

assertThat(fido).isEqualTo(fidosClone);

This will fail as isEqualTo() compares object references. If we want to compare their content instead, we can use isEqualToComparingFieldByFieldRecursively() like so:

assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);

Fido and fidosClone are equal when doing a recursive field by field comparison because each field of one object is compared to the field in the other object.

There are many other assertion methods that provide different ways to compare and contract objects and to examine and assert on their fields. In order to discover them all, refer to the official AbstractObjectAssert documentation.

4.4. Boolean Assertions

Some simple methods exist for truth testing:

  • isTrue()
  • isFalse()

Let’s see them in action:

assertThat("".isEmpty()).isTrue();

4.5. Iterable/Array Assertions

For an Iterable or an Array there are multiple ways of asserting that their content exist. One of the most common assertions would be to check if an Iterable or Array contains a given element:

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

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

or if a List is not empty:

assertThat(list).isNotEmpty();

or if a List starts with a given character. For example “1”:

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

Keep in mind that if you want to create more than one assertion for the same object, you can join them together easily.

Here is an example of an assertion that checks if a provided list is not empty, contains “1” element, does not contains any nulls and contains sequence of elements “2”, “3”:

assertThat(list)
  .isNotEmpty()
  .contains("1")
  .doesNotContainNull()
  .containsSequence("2", "3");

Of course many more possible assertions exist for those types. In order to discover them all, refer to the official AbstractIterableAssert documentation.

4.6. Character Assertions

Assertions for character types mostly involve comparisons and even checking if a given character is from a Unicode table.

Here is an example of an assertions that checks if a provided character is not ‘a’, is in Unicode table, is greater than ‘b’ and is lowercase:

assertThat(someCharacter)
  .isNotEqualTo('a')
  .inUnicode()
  .isGreaterThanOrEqualTo('b')
  .isLowerCase();

For a detailed list of all character types’ assertions, see AbstractCharacterAssert documentation.

4.7. Class Assertions

Assertions for Class type are mostly about checking its fields, Class types, presence of annotations and class finality.

If you want to assert that class Runnable is an interface, you need to simply write:

assertThat(Runnable.class).isInterface();

or if you want to check if one class is assignable from the other:

assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);

All possible Class assertions can be viewed in the AbstractClassAssert documentation.

4.8. File Assertions

File assertions are all about checking if a given File instance exists, is a directory or a file, has certain content, is readable, or has given extension.

Here you can see an example of an assertion that checks if a given file exists, is file and not a directory, can be readable and writable:

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

All possible Class assertions can be viewed in the AbstractFileAssert documentation.

4.9. Double/Float/Integer Assertions

Double/Float/Integer and Other Number Types

Numeric assertions are all about comparing numeric values within or without a given offset. For example, if you want to check if two values are equal according to a given precision we can do the following:

assertThat(5.1).isEqualTo(5, withPrecision(1d));

Notice that we are using already imported withPrecision(Double offset) helper method for generating Offset objects.

For more assertions, visit AbstractDoubleAssert documentation.

4.10. InputStream Assertions

There is only one InputStream-specific assertion available:

  • hasSameContentAs(InputStream expected)

and in action:

assertThat(given).hasSameContentAs(expected);

4.11. Map Assertions

Map assertions allow you to check if a map contains certain entry, set of entries, or keys/values separately.

And here you can see an example of an assertions that checks if a given map is not empty, contains numeric key “2”, does not contain numeric key “10” and contains entry: key: 2, value: “a”:

assertThat(map)
  .isNotEmpty()
  .containsKey(2)
  .doesNotContainKeys(10)
  .contains(entry(2, "a"));

For more assertions, see AbstractMapAssert documentation.

4.12. Throwable Assertions

Throwable assertions allow for example: inspecting exception’s messages, stacktraces, cause checking or verifying if an exception has been thrown already.

Let’s have a look at the example of an assertion that checks if a given exception was thrown and has a message ending with “c”:

assertThat(ex).hasNoCause().hasMessageEndingWith("c");

For more assertions, see AbstractThrowableAssert documentation.

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.

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>

6. Java 8

AssertJ takes full advantage of Java 8’s functional programming features. Let’s dive into an example and see it in action. First let’s see how we do it in Java 7:

assertThat(fellowshipOfTheRing)
  .filteredOn("race", HOBBIT)
  .containsOnly(sam, frodo, pippin, merry);

Here we are filtering a collection on the race Hobbit and in Java 8 we can do something like this:

assertThat(fellowshipOfTheRing)
  .filteredOn(character -> character.getRace().equals(HOBBIT))
  .containsOnly(sam, frodo, pippin, merry);

We will be exploring AssertJ’s Java8 capabilities in a future article from this series. The above examples were taken from AssertJ’s website.

7. Conclusion

In this article we briefly explored the possibilities that AssertJ gives us along with the most popular assertions for core Java types.

The implementation of all the examples and code snippets can be found in a GitHub project.

Get the early-bird price (20% Off) of my upcoming "Learn Spring Security" Course:

>> CHECK OUT THE COURSE


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>