有没有办法设置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);
}
...
答案 0 :(得分: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的源代码。