简体   繁体   English

如何在 Java 单元测试中断言无序的 HashSet 元素?

[英]How to assert unordered HashSet elements in Java Unit Test?

I have a Unit Test for a service method that returns an HashSet<T> and I get it in the test method as shown below:我有一个返回HashSet<T>的服务方法的单元测试,我在测试方法中得到它,如下所示:

Set<EmployeeDTO> result = employeeService.findAllByUuid(uuid);
        
// I also convert the set to list for accessing by index:
List<EmployeeDTO> resultList = new ArrayList<>(result);

And try to assert as shown below:并尝试断言如下所示:

assertEquals("Hans", resultList.get(0).getName());

However, there are 2 elements in the resultset and as expected, the order in the HashSet is changing.但是,结果集中有 2 个元素,正如预期的那样, HashSet中的顺序正在发生变化。 In this scene, how should I make assertions when I receive HashSet as return type of the tested method?在这个场景中,当我收到HashSet作为被测方法的返回类型时,我应该如何进行断言?

If the order can change, you can simply assert that the set contains the value, as the order changing means there is no reason why you should expect a specific value to occur at a specific index:如果顺序可以更改,您可以简单地断言该集合包含该值,因为顺序更改意味着您没有理由期望特定值出现在特定索引处:

@Test
void testSetContainsHans(String uuid) {
  Set<EmployeeDTO> result = employeeService.findAllByUuid(uuid);
  boolean containsHans = false;
  for (EmployeeDTO emp : result) {
    if ("Hans".equals(emp.getName()) {
      containsHans = true;
      break;
    }
  }
  assertTrue(containsHans, "No employee named Hans was found.");
}

This test will pass if the set returned by employeeService.findAllByUuid(uuid) contains at least one EmployeeDTO with a name of "Hans", or fail with a message of "No employee named Hans was found."如果employeeService.findAllByUuid(uuid)返回的集合包含至少一个名为“Hans”的EmployeeDTO ,则此测试将通过,或者失败并显示"No employee named Hans was found." if it doesn't.如果没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM