使用Mockito,我如何测试一个有限的循环'有布尔条件?

时间:2015-06-18 17:14:04

标签: mocking mockito

使用Mockito,如何测试有限循环' ?

我有一个我想要测试的方法,如下所示:

public void dismissSearchAreaSuggestions()
{
    while (areSearchAreaSuggestionsVisible())
    {
        clickSearchAreaField();
        Sleeper.sleepTight(CostTestBase.HALF_SECOND);
    }
}

而且,我想对它进行测试,以便前两个调用“#SearchAreaSuggestionsVisible'返回TRUE,如下:

Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS, 
  TestBase.ONE_SECOND)).thenReturn(Boolean.TRUE);

但是,第三个电话是假的。

Mockito.when(mockElementState.isElementFoundAndVisible(LandingPage.ADDRESS_SUGGESTIONS, 
  TestBase.ONE_SECOND)).thenReturn(Boolean.FALSE);

我怎么能用Mockito在一个单一的测试方法中做到这一点?

到目前为止,这是我的测试类:

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

1 个答案:

答案 0 :(得分:2)

只要您将所有存根作为同一链的一部分,Mockito将按顺序继续执行它们,始终重复最后一次调用。

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

您也可以使用此语法执行此操作...

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

...如果行动都没有返回值,这可以派上用场。

// 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!"));

如果您希望事情变得更复杂,请考虑编写Answer