0

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?

  • You can compare to predefined set https://stackoverflow.com/questions/44355737/how-to-compare-two-hash-sets-in-java – Ori Marko Jun 22 '22 at 13:54
  • @user7294900 Thanks for reply, but I need to compare by getting parameters inside Set. How can I do that? –  Jun 22 '22 at 18:40
  • Has anybody else have never needed to compare hashset values in unit test? Any help please? –  Jun 23 '22 at 06:23

1 Answers1

0

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.

JustAnotherDeveloper
  • 2,061
  • 2
  • 10
  • 24