jMock - allowing() a call multiple times with different results

时光怂恿深爱的人放手 提交于 2019-12-12 04:56:09

问题


I want to call allowing() several times and provide different results. But I'm finding that the first allowing() specification absorbs all the calls and I can't change the return value.

@Test
public void example() {
    timeNow(100);
    // do something

    timeNow(105);
    // do something else
}

private void timeNow(final long timeNow) {
    context.checking(new Expectations() {{
        allowing(clock).timeNow(); will(returnValue(timeNow));
    }});
}

If I change allowing(clock) to oneOf(clock) it works fine. But ideally I want to use allowing() and not over-specify that the clock is called only once. Is there any way to do it?


回答1:


I would recommend taking a look at states - they allow you to change which expectation to use based on what "state" the test is in.

@Auto private States clockState;
@Test
public void example() {
    clockState.startsAs("first");
    timeNow(100);
    // do something

    clockState.become("second");
    timeNow(105);
    // do something else
}

private void timeNow(final long timeNow) {
    context.checking(new Expectations() {{
        allowing(clock).timeNow(); will(returnValue(timeNow));
        when(clockState.is("first"));

        allowing(clock).timeNow(); will(returnValue(timeNow + 100));
        when(clockState.is("second"));
    }});
}


来源:https://stackoverflow.com/questions/28853650/jmock-allowing-a-call-multiple-times-with-different-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!