简体   繁体   中英

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:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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