Extract Values Using AssertJ in Java

06 May 2023 Balmiki Mandal 0 Core Java

Using AssertJ to Extract Values in Java

AssertJ is an open-source Assertion library for Java that enables developers to express their assertions in a natural and easy-to-read way. One of the most useful features of AssertJ is its ability to extract values from complex objects, making it easy to test conditions and assertions without having to write boilerplate code.

In this article, we’ll look at how to use AssertJ to extract values from complex Java objects. We’ll focus on how assertThat() works, how to extract single and multiple values, and how it can be used with stream operations. At the end, there are some useful tips for debugging extractions.

How to Use assertThat() to Extract Values

assertThat() is the main assertion entry point. It’s not the only one, but it’s the most common and versatile one. It has two main variations:

  • assertThat(T actual) – Checks the actual value
  • assertThat(Supplier<T> supplier) – Allows you to defer evaluation until the assertion is actually evaluated

The assertion methods that come after assertThat() are dependent on the type of the argument you provide. For example, if you pass a String as the argument, you’ll get methods like isEqualTo(), matches(), and containsOnlyDigits(). If you pass an array or a list, you’ll get methods like hasSize() and contains().

In the context of extractions, you can pass an object as the argument and call the extracting() method. This will allow you to extract data from the object using lambda expressions. Here’s an example where we extract a list of names from a Person object:

List<Person> people = ...; // initializing the list

List<String> names = assertThat(people).extracting(Person::getName)
               .asList();

In this case, we use the getName() method to extract the name from each Person object.

Extracting Single Values

If you want to extract a single value from a collection or a map, you can use the extractingResultOf() method. This method takes two arguments: a function and an object. The function will be used to extract the value from the object. Here’s an example where we extract a single value from a map:

Map<String, Integer> scores = ...; // initializing the map

Integer maxScore = assertThat(scores).extractingResultOf("max", 
                       (map) -> map.values().stream().max(Integer::compareTo).get())
               .asInstanceOf(Integer.class);

In this example, we use a lambda expression to extract the maximum value from the map. We then use the asInstanceOf() method to cast the result to an Integer.

Extracting Multiple Values

If you want to extract multiple values from an object, you can use the extractingInAnyOrder() or extractingOnlyElementsOfType() methods. These methods take two arguments: a function and a type. The function will be used to extract the values, and the type will restrict the values to those of the given type.

Here’s an example where we extract a list of integers from a list of objects:

List<Object> objects = ...; // initializing the list

List<Integer> integers = assertThat(objects).extractingOnlyElementsOfType(Integer.class)
                          .asList();

Using Stream Operations with assertThat()

assertThat() can also be used in combination with stream operations. This allows you to combine the extraction of data with the filtering and transformation of data. Here’s an example where we extract a list of people with a certain age:

List<Person> people = ...; // initializing the list

List<Person> peopleWithCertainAge = assertThat(people).extracting(Person::getAge)
                              .filteredOn(age -> age == 25)
                              .asList(); // list of people with age 25

Debugging Extractions

When extracting values from complex objects, it’s not uncommon to run into issues. Fortunately, AssertJ provides some useful debugging tools that can help you track down problems. These tools include the debug() method, which prints the intermediate state of the extraction, and the getErrors() method, which returns a list of errors.

Here’s an example of how to use the debug() method:

List<Person> people = ...; // initializing the list

assertThat(people).extracting(Person::getName)
   .debug() // prints the intermediate state of the extraction
   .asList();

These debugging methods can help you track down any errors with your extractions.

Conclusion

In this article, we looked at how to use AssertJ to extract values from complex Java objects. We focused on how to use the assertThat() method, how to extract single and multiple values, and how to use stream operations with assertThat(). Finally, we saw how to debug your extractions using the debug() and getErrors() methods.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.