首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Jmock循环连续调用

Jmock循环连续调用
EN

Stack Overflow用户
提问于 2013-07-03 17:16:44
回答 1查看 921关注 0票数 0

有任何方法来设置JMock的onConsecutiveCalls方法来循环回传递到传递的参数列表末尾的第一个操作吗?在下面的示例代码中,我希望模拟返回true->false->true->Ad infinitum

模拟设置:

代码语言:javascript
复制
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方法:

代码语言:javascript
复制
...
for (String id:idList){
  boolean first = getMyService().doSomething(methodParam1, someString);
  boolean second =  getMyService().doSomething(anotherString, id);
}
...
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-03 17:39:15

我通过在我的测试类中添加以下内容来解决这个问题,然后调用onRecurringConsecutiveCalls()代替onConsecutiveCalls()

附加代码:

代码语言:javascript
复制
/**
 * 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的源代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17454313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档