Search code examples
javajmockit

Return different value depends on times value


There is code which calls method in the cycle, I want to test the case when the method throws exception in for 2 first attempts and then returns a valid value. Using JMockit I write the following code:

new Expectations() {{
    someService.call(anyString);
    times = 2;
    result = exception;
    someService.call(anyString);
    result = entity;
}};

At this case it someService::call always returns entity.

How can I return an exception for first two calls and then return entity in test?


Solution

  • Like with any other mocking API, record each desired result of the expectation, in the desired sequence:

    new Expectations() {{
        someService.call(anyString);
        result = exception;
        result = exception;
        result = entity;
    }};