This is an example of a pattern I've encountered a lot recently. I have a method to be tested that takes a List and may invoke some other method(s) for each item in the list. To test this I define an Iterator with the expected call parameters and a loop in the JMock expectations to check the call is made against each item of the iterator (see trivial example below).
I've had a look at the Hamcrest matchers but haven't found something that tests for this (or have misunderstood how the available matchers work). Does anyone have a more elegant approach?
package com.hsbc.maven.versionupdater;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.maven.plugin.testing.AbstractMojoTestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.Sequence;
import org.jmock.internal.NamedSequence;
public class FooTest extends AbstractMojoTestCase {
public interface Bar {
void doIt(String arg);
}
public class Foo {
private Bar bar;
public void executeEven(final List<String> allParameters) {
for (int i = 0; i < allParameters.size(); i++) {
if (i % 2 == 0) {
bar.doIt(allParameters.get(i));
}
}
}
public Bar getBar() {
return bar;
}
public void setBar(final Bar bar) {
this.bar = bar;
}
}
public void testExecuteEven() {
Mockery mockery = new Mockery();
final Bar bar = mockery.mock(Bar.class);
final Sequence sequence = new NamedSequence("sequence");
final List<String> allParameters = new ArrayList<String>();
final List<String> expectedParameters = new ArrayList<String>();
for (int i = 0; i < 3; i++) {
allParameters.add("param" + i);
if (i % 2 == 0) {
expectedParameters.add("param" + i);
}
}
final Iterator<String> iter = expectedParameters.iterator();
mockery.checking(new Expectations() {
{
while (iter.hasNext()) {
one(bar).doIt(iter.next());
inSequence(sequence);
}
}
});
Foo subject = new Foo();
subject.setBar(bar);
subject.executeEven(allParameters);
mockery.assertIsSatisfied();
}
}