0

JMock の onConsecutiveCalls メソッドをセットアップして、渡されたパラメータのリストの最後に到達したら最初に渡された Action にループバックする方法はありますか? 以下のサンプル コードでは、モックが を返すようにしtrue->false->true->Ad infinitumます。

モックのセットアップ:

final MyService myServiceMocked = mockery.mock(MyService.class);

mockery.checking(new Expectations() {{  
  atLeast(1).of(myServiceMocked).doSomething(with(any(String.class)), with(any(String.class))); 
  will (onConsecutiveCalls(
    returnValue(true),
    returnValue(false)
  ));
}});

doSomething メソッドを呼び出すメソッド:

...
for (String id:idList){
  boolean first = getMyService().doSomething(methodParam1, someString);
  boolean second =  getMyService().doSomething(anotherString, id);
}
...
4

1 に答える 1

0

onRecurringConsecutiveCalls()この問題を回避するには、テスト クラスに以下を追加し、代わりに を呼び出しonConsecutiveCalls()ます。

追加コード:

/**
 * Recurring version of {@link org.jmock.Expectations#onConsecutiveCalls(Action...)}
 * When last action is executed, loops back to first.
 * @param actions Actions to execute.
 * @return An action sequence that will loop through the given actions.
 */
public Action onRecurringConsecutiveCalls(Action...actions) {
    return new RecurringActionSequence(actions);
}
/**
 * Recurring version of {@link org.jmock.lib.action.ActionSequence ActionSequence}
 * When last action is executed, loops back to first.
 * @author AnthonyW
 */
public class RecurringActionSequence extends ActionSequence {
    List<Action> actions;
    Iterator<Action> iterator;

    /**
     * Recurring version of {@link org.jmock.lib.action.ActionSequence#ActionSequence(Action...) ActionSequence}
     * When last action is executed, loops back to first.
     * @param actions Actions to execute.
     */
    public RecurringActionSequence(Action... actions) {
        this.actions = new ArrayList<Action>(Arrays.asList(actions));
        resetIterator();
    }

    @Override
    public Object invoke(Invocation invocation) throws Throwable {
        if (iterator.hasNext()) 
            return iterator.next().invoke(invocation);
        else
            return resetIterator().next().invoke(invocation);
    }

    /**
     * Resets iterator to starting position.
     * @return <code>this.iterator</code> for chain calls.
     */
    private Iterator<Action> resetIterator() {
        this.iterator = this.actions.iterator();
        return this.iterator;
    }
}

注:このコードは、JMock 2.1 のソース コードに基づいています。

于 2013-07-03T17:39:15.787 に答える