java 使用AssertJ检查单元测试中Map条目内的列表

9lowa7mx  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(160)

我想使用AssertJ库检查单元测试中Map值内的列表:

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

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

在一个Map我有这个:

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

如何检查组内的列表?我想我应该使用一个提取方法,flatExtracting方法,但我不知道如何操作。

lh80um4z

lh80um4z1#

假设character是输入键,player1player2是内部列表的预期内容,您可以编写:

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

或类型安全,如果Group提供getPlayers()

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

参考:

  • extracting(String, InstanceOfAssertFactory)
  • extracting(Function, InstanceOfAssertFactory)
  • Assertions.as(InstanceOfAssertFactory)
  • InstanceOfAssertFactories.LIST
  • InstanceOfAssertFactories.list(Class)
elcex8rz

elcex8rz2#

for (Map.Entry<Character, Group> entry : generatedGroups.entrySet()) {
    
    List<Player> players = entry.getValue().getPlayers();
    // Do your check here
}
y53ybaqx

y53ybaqx3#

以下是与特定用例略有不同的答案。
我们希望AssertResponse对象中是否存在头。下面是使用AssertJAssert验证头ResponseEntity.ok().contentType(APPLICATION_JSON)的单元测试

assertThat(response).hasFieldOrPropertyWithValue("statusCode", OK)
          .extracting("headers")
          .isInstanceOf(HttpHeaders.class)
          .hasFieldOrPropertyWithValue("Content-Type",List.of(APPLICATION_JSON_VALUE));

相关问题