Open In App

JUnit5 – Map Assertions With AssertJ with Example Maven Project

Last Updated : 31 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, by seeing a sample project that involves a few characters in the “friends” web series and checking their names against correct professions as fun. For storing names and their professions, we need a “HashMap” facility. In that let us store their names and professions. With that, we need to check all the features applicable to JUnit5 Assertions with AssertJ.

Example Maven Project

Project Structure:

Project Structure

 

This is a Maven project. Hence all dependencies need to be given in

pom.xml

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>gfg.sample.junit5</groupId>
    <artifactId>sampleproject-assertions-with-assertj</artifactId>
    <version>0.1</version>
    <name>Writing Assertions With AssertJ For a Friends Webseries Characters</name>
    <description>
        This example demonstrates how we can write assertions with AssertJ For a Friends Webseries Characters.
    </description>
  
    <properties>
        <jdk.version>1.8</jdk.version>
        <junit.jupiter.version>5.8.2</junit.jupiter.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
  
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>${junit.jupiter.version}</version>
            <scope>test</scope>
        </dependency>
        
          <!-- This is mandatory as we are doing assertj -->
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>3.21.0</version>
            <scope>test</scope>
        </dependency>
      <!-- This is mandatory as we are doing assertj -->
        
    </dependencies>
    <build>
        <finalName>sampleproject-assertions-with-assertj</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
</project>


FriendsWebSeriesAssertionTestForMap.java

Java




import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
  
@DisplayName("Writing assertions for maps - Taking few characters and their professions")
class FriendsWebSeriesAssertionTestForMap {
    
    private static final String INCORRECT_USERNAMEKEY = "monica";
    private static final String USERNAME1KEY = "rachel";
    private static final String USERNAME1VALUE = "Fashiondesigner";
    private static final String USERNAME2KEY = "ross";
    private static final String USERNAME2VALUE = "Paleontologist";
  
    private Map<String, String> userNameMap;
  
    @BeforeEach
    void creationAndInitializationOfFriendsWebSeriesUsers() {
        userNameMap = new HashMap<>();
        userNameMap.put(USERNAME1KEY, USERNAME1VALUE);
        userNameMap.put(USERNAME2KEY, USERNAME2VALUE);
    }
  
    @Nested
    @DisplayName("checking for the character map contains the given key and value")
    class VerifyThatFriendsWebseriesContainsGivenUserNameKeyAndValue {
  
        @Test
        @DisplayName("Should contain the correct key and value")
        void shouldContainCorrectKey() {
            assertThat(userNameMap).containsKey(USERNAME1KEY);
            assertThat(userNameMap).containsKey(USERNAME2KEY);
            assertThat(userNameMap).containsValue(USERNAME1VALUE);
            assertThat(userNameMap).containsValue(USERNAME2VALUE);
        }
  
        @Test
        @DisplayName("Should contain the correct key and value (with custom error message)")
        void shouldContainCorrectKeyAndValueWithCustomErrorMessage() {
            assertThat(userNameMap).overridingErrorMessage("The map doesn't contain the key: %s", USERNAME1KEY)
                    .containsKey(USERNAME1KEY);
            assertThat(userNameMap).overridingErrorMessage("The map doesn't contain the value: %s", USERNAME2KEY)
                    .containsValue(USERNAME2VALUE);
        }
    }
  
    @Nested
    @DisplayName("Verification of the usermap does not contain the given usernamekey")
    class VerificationOfTheMapDoesNotContainGivenUserNameKey {
  
        @Test
        @DisplayName("Should not contain the incorrect userNameKey")
        void checkTheNonExistenceOfIncorrectUserNameKey() {
            assertThat(userNameMap).doesNotContainKey(INCORRECT_USERNAMEKEY);
        }
  
        @Test
        @DisplayName("Should not contain the incorrect key (with custom error message)")
        void checkTheNonExistenceOfIncorrectUserNameKeyWithCustomErrorMessage() {
            assertThat(userNameMap).overridingErrorMessage("The map contains the key: %s", INCORRECT_USERNAMEKEY)
                    .doesNotContainKey(INCORRECT_USERNAMEKEY);
        }
    }
  
    @Nested
    @DisplayName("Checking for correct username key and values")
    class ConcurrenceOfCorrectUserNameWithValues {
  
        @Test
        @DisplayName("Should contain the correct usernames and uservalues")
        void checkingForCorrectUserNameKeyAndValue() {
            assertThat(userNameMap).containsEntry(USERNAME1KEY, USERNAME1VALUE);
            assertThat(userNameMap).containsEntry(USERNAME2KEY, USERNAME2VALUE);
        }
  
        @Test
        @DisplayName("Checking for correct username key and values (with custom error message)")
        void checkingForCorrectUserNameKeyAndValueWithCustomErrorMessage() {
            assertThat(userNameMap).overridingErrorMessage("The map didn't contain the value: %s for the key: %s",
                    USERNAME1VALUE, USERNAME1KEY).containsEntry(USERNAME1KEY, USERNAME1VALUE);
        }
    }
  
    @Nested
    @DisplayName("Checking For matched or mismatched entries")
    class CheckForMismatchedEntries {
        @Test
        @DisplayName("Checking for the existence of the given entry")
        void checkForExistenceOfGivenEntry() {
            assertThat(userNameMap).doesNotContainEntry(INCORRECT_USERNAMEKEY, USERNAME1VALUE);
            assertThat(userNameMap).doesNotContainEntry(USERNAME2KEY, USERNAME1VALUE);
        }
  
        @Test
        @DisplayName("Checking for the existence of the given entry (with custom error message)")
        void checkForExistenceOfGivenEntryWithCustomErrorMessage() {
            assertThat(userNameMap)
                    .overridingErrorMessage(
                            "Expected the map to not contain the value: %s for the key: %s but it contained it",
                            USERNAME1VALUE, INCORRECT_USERNAMEKEY)
                    .doesNotContainEntry(INCORRECT_USERNAMEKEY, USERNAME1VALUE);
        }
    }
  
    @Nested
    @DisplayName("Check for UserNameKey and UserNameValue")
    class CheckForUserNameValueFromMap {
  
        @Nested
        @DisplayName("When the usernamevalue is found")
        class WhenUserNameValueIsFound {
  
            @Test
            @DisplayName("Check for the found value")
            void checkForFoundUserNameValue() {
                final String returned = userNameMap.get(USERNAME1KEY);
                assertThat(returned).isEqualTo(USERNAME1VALUE);
                assertThat(userNameMap.get(USERNAME2KEY)).isEqualTo(USERNAME2VALUE);
            }
  
            @Test
            @DisplayName("Check for the found value (with custom error message)")
            void checkForFoundUserNameValueWithCustomErrorMessage() {
                final String returned = userNameMap.get(USERNAME1KEY);
                assertThat(returned).overridingErrorMessage(
                        "Expected the map to return: %s by using the key: %s but it returned: %s", USERNAME1VALUE,
                        USERNAME1KEY, returned).isEqualTo(USERNAME1VALUE);
            }
        }
  
        @Nested
        @DisplayName("When the usernamevalue is not found")
        class WhenUserNameValueIsNotFound {
  
            @Test
            @DisplayName("Check the returned null value")
            void checkForReturnNull() {
                final String returned = userNameMap.get(INCORRECT_USERNAMEKEY);
                assertThat(returned).isNull();
            }
  
            @Test
            @DisplayName("Check the returned null value (with custom error message)")
            void checkForReturnNullWithCustomErrorMessage() {
                final String returned = userNameMap.get(INCORRECT_USERNAMEKEY);
                assertThat(returned)
                        .overridingErrorMessage("Expected the map to return null for the key: %s but it returned: %s",
                                USERNAME1KEY, returned)
                        .isNull();
                assertThat(returned)
                        .overridingErrorMessage("Expected the map to return null for the key: %s but it returned: %s",
                                USERNAME2KEY, returned)
                        .isNull();
            }
        }
    }
}


On running the above program, the below output is seen. First, we can run whole tests or even part by part as well. In eclipse, depending on the cursor location the test is picked up and executed it

 

And hence the tests whatever present under “FriendsWebSeriesAssertionTestForMap” are shown here.

 

Usages of

  • @DisplayName: With this, easily one can use the customized display name.
  • @Nested: Hierarchically we can keep the test and there is no limit to the depth of the class hierarchy

A nested class can contain one @BeforeEach method and one @AfterEach method.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads