jMock - allowing() a call multiple times with diff

2019-09-06 00:24发布

问题:

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"));
    }});
}


标签: java jmock