Reputation: 29689
Using Mockito, how do I test a 'finite loop' ?
I have a method I want to test that looks like this:
public void dismissSearchAreaSuggestions()
{
while (areSearchAreaSuggestionsVisible())
{
clickSearchAreaField();
Sleeper.sleepTight(CostTestBase.HALF_SECOND);
}
}
And, I want to test it so that the first 2 calls to 'areSearchAreaSuggestionsVisible' return a TRUE, like so:
Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS,
TestBase.ONE_SECOND)).thenReturn(Boolean.TRUE);
But, the third call is FALSE.
Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS,
TestBase.ONE_SECOND)).thenReturn(Boolean.FALSE);
How could I do that with Mockito in one single test method?
Here is my test class so far:
@Test
public void testDismissSearchAreaSuggestionsWhenVisible()
{
Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS,
CostTestBase.ONE_SECOND)).thenReturn(Boolean.TRUE);
landingPage.dismissSearchAreaSuggestions();
Mockito.verify(mockElementState).isElementFoundAndVisible(LandingPage
.ADDRESS_SUGGESTIONS, CostTestBase.ONE_SECOND);
}
Upvotes: 1
Views: 4047
Reputation: 95754
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.
Upvotes: 4