Search code examples
jmockit

Jmockit: impossible to use returns() with collections and multiple calls?


The function I want to mock:

class Bar {
  public Set<Foo> getFoos();
}

The code under test:

for (int i = 0; i < n; ++i) {
  Bar bar = computeBar();
  for (Foo f : bar.getFoos()) {
    // code
  }
}

Expectations block:

new Expectations() {{
  bar.getFoos();
  returns(/* what should I put here?? */);
}};

Solution

  • Either write

    new Expectations() {{ bar.getFoos(); returns(foo1, foo2, foo3); }};
    

    to return a single set, or

    final Set<Foo> foos1 = new HashSet<Foo>(asList(foo1, foo2));
    final Set<Foo> foos2 = new HashSet<Foo>(asList(foo3, foo4, foo5));
    new Expectations() {{ bar.getFoos(); returns(foos1, foos2); }};
    

    to return a sequence of sets.