Using Mockito, how do I test a 'finite loop' with a boolean condition?

前端 未结 1 728
庸人自扰
庸人自扰 2021-01-17 02:11

Using Mockito, how do I test a \'finite loop\' ?

I have a method I want to test that looks like this:

public void dismissSearchAreaSuggestions()
{
           


        
1条回答
  •  失恋的感觉
    2021-01-17 03:07

    As long as you make all of your stubs a part of the same chain, Mockito will proceed through them in sequence, always repeating the final call.

    // returns false, false, true, true, true...
    when(your.mockedCall(param))'
        .thenReturn(Boolean.FALSE, Boolean.FALSE, Boolean.TRUE);
    

    You can also do so with this syntax...

    // returns false, false, true, true, true...
    when(your.mockedCall(param))
        .thenReturn(Boolean.FALSE)
        .thenReturn(Boolean.FALSE)
        .thenReturn(Boolean.TRUE);
    

    ...which can come in handy if the actions aren't all return values.

    // returns false, false, true, then throws an exception
    when(your.mockedCall(param))
        .thenReturn(Boolean.FALSE)
        .thenReturn(Boolean.FALSE)
        .thenReturn(Boolean.TRUE)
        .thenThrow(new Exception("Called too many times!"));
    

    If you want things to get more complex than that, consider writing an Answer.

    0 讨论(0)
提交回复
热议问题