使用Mockito,如何在布尔条件下测试“有限循环"? [英] Using Mockito, how do I test a 'finite loop' with a boolean condition?
问题描述
使用Mockito,如何测试有限循环"?
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);
}
}
而且,我想对其进行测试,以使对"areSearchAreaSuggestionsVisible"的前两个调用返回TRUE,如下所示:
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);
但是,第三个电话是FALSE.
But, the third call is FALSE.
Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS,
TestBase.ONE_SECOND)).thenReturn(Boolean.FALSE);
我如何在一种测试方法中使用Mockito做到这一点?
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);
}
推荐答案
只要您将所有存根都设为同一链的一部分,Mockito就会按顺序进行遍历,并始终重复最后的电话.
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.
这篇关于使用Mockito,如何在布尔条件下测试“有限循环"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!