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

Asserting Nested Map With JUnit

$
0
0

1. Overview

In this tutorial, we’ll go through some of the different ways of asserting the presence of a nested map inside an outer map. Mostly, we’ll discuss the JUnit Jupiter API and the Hamcrest API.

2. Asserting by Using Jupiter API

For this article, we’ll use Junit 5, and hence let’s look at the Maven dependency:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version>
    <scope>test</scope>
</dependency>

Let’s take as an example a Map object with an outer map and an inner map. The outer map has an address key with the inner map as the value. It also has a name key with the value John:

{
    "name":"John",
    "address":{"city":"Chicago"}
}

With examples, we’ll assert the presence of a key-value pair in the inner map.

Let’s begin with the basic assertTrue() method from Jupiter API:

@Test
void givenNestedMap_whenUseJupiterAssertTrueWithCasting_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Object> outerMap = Map.of("address", innerMap);
    assertTrue(outerMap.containsKey("address")
      && ((Map<String, Object>)outerMap.get("address")).get("city").equals("Chicago"));
}

We’ve used boolean expressions to evaluate if the innerMap is present in the outerMap. Then, we checked if the inner map had a city key with the value Chicago.

However, the readability is lost due to the typecasting used above to avoid the compilation error. Let’s try to fix it:

@Test
void givenNestedMap_whenUseJupiterAssertTrueWithoutCasting_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Map<String, Object>> outerMap = Map.of("address", innerMap);
    assertTrue(outerMap.containsKey("address") && outerMap.get("address").get("city").equals("Chicago"));
}

Now, we changed the way we declared the outer map earlier. We declared it as Map<String, Map<String, Object>> instead of Map<String, Object>. With this, we avoided typecasting and achieved a little more readable code.

But, if the test fails we’ll not know exactly which assertion failed. To resolve this, let’s bring in the method assertAll():

@Test
void givenNestedMap_whenUseJupiterAssertAllAndAssertTrue_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Map<String, Object>> outerMap = Map.of("address", innerMap);
    assertAll(
      () -> assertTrue(outerMap.containsKey("address")),
      () -> assertEquals(outerMap.get("address").get("city"), "Chicago")
    );
}

We moved the boolean expressions to the methods assertTrue() and assertEquals() within assertAll(). Hence, now we’ll know the exact failure. Moreover, it has improved the readability as well.

3. Asserting by Using Hamcrest API

Hamcrest Library offers a very flexible framework for writing Junit tests with the help of Matchers. We’ll use its out-of-the-box Matchers and develop a custom Matcher using its framework to verify the presence of a key-value pair in a nested map.

3.1. With Existing Matchers

For using the Hamcrest library we’ll have to update the Maven dependencies in the pom.xml file:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

Before we jump into examples, let’s first understand the support for testing a Map in the Hamcrest library. Hamcrest supports the following Matchers which can be used with the method assertThat():

  • hasEntry() – Creates a matcher for Maps matching when the examined Map contains at least one entry whose key equals the specified key and whose value equals the specified value
  • hasKey() – Creates a matcher for Maps matching when the examined Map contains at least one key that satisfies the specified matcher
  • hasValue() – Creates a matcher for Maps matching when the examined Map contains at least one value that satisfies the specified valueMatcher

Let’s start with a basic example just like in the earlier section but we’ll use the methods assertThat() and hasEntry():

@Test
void givenNestedMap_whenUseHamcrestAssertThatWithCasting_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Object> outerMap = Map.of("address", innerMap);
    assertThat((Map<String, Object>)outerMap.get("address"), hasEntry("city", "Chicago"));
}

Apart from the ugly typecasting, the test is considerably easier to read and follow. However, we missed checking whether the outer map has the key address before getting its value.

Shouldn’t we try fixing the above test? Let’s use hasKey() and hasEntry() to assert the presence of the inner map:

@Test
void givenNestedMap_whenUseHamcrestAssertThat_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Map<String, Object>> outerMap = Map.of("address", innerMap);
    assertAll(
      () -> assertThat(outerMap, hasKey("address")),
      () -> assertThat(outerMap.get("address"), hasEntry("city", "Chicago"))
    );
}

Interestingly, we’ve combined assertAll() from the Jupiter library with the Hamcrest library to test the map. Also to remove the typecast we tweaked the definition of the variable outerMap.

Let’s see another way of doing the same thing with just the Hamcrest library:

@Test
void givenNestedMapOfStringAndObject_whenUseHamcrestAssertThat_thenTest() {
    Map<String, Object> innerMap = Map.of("city", "Chicago");
    Map<String, Map<String, Object>> outerMap = Map.of("address", innerMap);
    assertThat(outerMap, hasEntry(equalTo("address"), hasEntry("city", "Chicago")));
}

Surprisingly, we could nest the hasEntry() method. This was possible with the help of the equalTo() method. Without it, the method would compile but the assertion would fail.

3.2. With a Custom Matcher

So far, we tried existing methods to check the presence of the nested map. Let’s try to create a custom Matcher by extending the TypeSafeMatcher class in the Hamcrest library.

public class NestedMapMatcher<K, V> extends TypeSafeMatcher<Map<K, Object>> {
    private K key;
    private V subMapValue;
    public NestedMapMatcher(K key, V subMapValue) {
        this.key = key;
        this.subMapValue = subMapValue;
    }
    @Override
    protected boolean matchesSafely(Map<K, Object> item) {
        if (item.containsKey(key)) {
            Object actualValue = item.get(key);
            return subMapValue.equals(actualValue);
        }
        return false;
    }
    @Override
    public void describeTo(Description description) {
        description.appendText("a map containing key ").appendValue(key)
                .appendText(" with value ").appendValue(subMapValue);
    }
    public static <K, V> Matcher<V> hasNestedMapEntry(K key, V expectedValue) {
        return new NestedMapMatcher(key, expectedValue);
    }
}

We had to override the matchSafely() method for checking the nested map.

Let’s see how we can use it:

@Test
void givenNestedMapOfStringAndObject_whenUseHamcrestAssertThatAndCustomMatcher_thenTest() {
    Map<String, Object> innerMap = Map.of
      (
        "city", "Chicago",
        "zip", "10005"
      );
    Map<String, Map<String, Object>> outerMap = Map.of("address", innerMap);
    assertThat(outerMap, hasNestedMapEntry("address", innerMap));
}

Visibly, the expression to check the nested map in the method assertThat() is far more simplified. We just had to call the hasNestedMapEntry() method to check the innerMap. Additionally, it compares the whole inner map, unlike the earlier checks where only one entry was checked.

Interestingly the custom Matcher works even if we define the outer map as Map(String, Object). We weren’t required to do any typecasting as well:

@Test
void givenOuterMapOfStringAndObjectAndInnerMap_whenUseHamcrestAssertThatAndCustomMatcher_thenTest() {
    Map<String, Object> innerMap = Map.of
      (
        "city", "Chicago",
        "zip", "10005"
      );
    Map<String, Object> outerMap = Map.of("address", innerMap);
    assertThat(outerMap, hasNestedMapEntry("address", innerMap));
}

4. Conclusion

In this article, we discussed the different ways to test the presence of a key-value in an inner nested map. We explored the Jupiter as well as the Hamcrest APIs.

Hamcrest provides some excellent out-of-the-box methods to support the assertions on nested maps. This prevents the use of boiler-plate code and hence helps in writing the tests in a more declarative way. Still, we had to write a custom Matcher to make the assertion more intuitive and support asserting multiple entries in the nested map.

As usual, the code used in this article can be found over on GitHub.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles



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