wxkevin
wxkevin

Reputation: 1654

How can you determine elements in a collection when Unit testing a void method?

I have a void method similar to this

public void handle(MyObject myObject) {
   Set<String> mySet = new HashSet<String>();
   mySet.addAll(myObject.getStuff();

   ...

   mySet.addAll(someOtherList);

   ...

   myService.doSomething(mySet);
}

I am using Mockito. I have mocked myService and I am verifying that myService.doSomething(mySet) gets called with any Set like this:

verify(myService).doSomething(any(Set.class));

But I want to verify the expected contents of the set. I tried something like this:

Set<String> expected = new HashSet<String>();
expected.add("item1");
expected.add("item2");
verify(myService).doSomething(expected);

This verified failed because due to "Argument(s) are different" as expected was [item1,item2] while actual was [item2,item1]. So the content is the same but not in the correct order.

How can I check that the contents are the same without changing the collection being used that maintains order?

Upvotes: 0

Views: 72

Answers (1)

Duncan Jones
Duncan Jones

Reputation: 69369

I wonder if you've simplified your example too much? Two Set instances will be equal provided that they contain the same objects, regardless of order.

See my example test below, which passes.

@Test
public void test() throws Exception {

  Foo foo = mock(Foo.class);

  Set<String> set = new HashSet<>();
  set.add("a");
  set.add("b");

  foo.doSomething(set);

  Set<String> set2 = new HashSet<>();
  set2.add("b");
  set2.add("a");

  verify(foo).doSomething(set2);
}

public interface Foo {
  void doSomething(Set<String> strings);
}

Upvotes: 2

Related Questions