Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a neater way of testing calls to mocked methods for each item in a list
    primarykey
    data
    text
    <p>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).</p> <p>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?</p> <pre><code>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&lt;String&gt; allParameters) { for (int i = 0; i &lt; 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&lt;String&gt; allParameters = new ArrayList&lt;String&gt;(); final List&lt;String&gt; expectedParameters = new ArrayList&lt;String&gt;(); for (int i = 0; i &lt; 3; i++) { allParameters.add("param" + i); if (i % 2 == 0) { expectedParameters.add("param" + i); } } final Iterator&lt;String&gt; 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(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload