如何在Java单元测试中主张无序的标签元素?

发布于 2025-02-09 11:18:12 字数 512 浏览 2 评论 0原文

我对服务方法进行了单元测试,该方法返回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);

但是请尝试断言如下:

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

但是,但是,中有2个元素结果集和预期的是,HashSet中的顺序正在更改。在这个场景中,当我收到HashSet作为测试方法的返回类型时,我应该如何做出断言?

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:

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. In this scene, how should I make assertions when I receive HashSet as return type of the tested method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雾里花 2025-02-16 11:18:12

如果订单可以更改,您可以简单地断言该集合包含该值,因为更改订单没有理由您应该期望在特定索引处发生特定值:

@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.");
}

如果由<<<<< code> firmanservice.findallbyuuid(uuid)至少包含一个opplyeedto带有“汉斯”的名称,或者没有找到的消息“没有找到名为Hans的员工”。如果没有。

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." if it doesn't.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文