eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI (cat= Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

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.11.0-M2</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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)