Search code examples
javaunit-testingassertj

Check a list inside a Map entry in a unit test using AssertJ


I want to check a list that is inside a Map value in a unit test using the AssertJ library:

public class Group {
    List<Player> players = new ArrayList<>();

    public Group(List<Player> players) {
        this.players.addAll(players);
    }
}
Map<Character, Group> generatedGroups = receiveFromAnyMethod();

Inside a Map I have this:

A: Group A -> players(playerA, playerB)

How I check a list inside a Group? I think I should use a extracting, flatExtracting methods, but I don't know how.


Solution

  • Assuming that character is the input key, and player1 and player2 are the expected content of the inner list, you can write:

    assertThat(generatedGroups.get(character))
      .extracting("players", as(InstanceOfAssertFactories.LIST))
      .containsExactly(player1, player2);
    

    or with type safety, in case Group offers a getPlayers():

    assertThat(generatedGroups.get(character))
      .extracting(Group::getPlayers, as(InstanceOfAssertFactories.LIST))
      .containsExactly(player1, player2);
    

    Reference: