有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Mockito模拟,我如何用布尔条件测试“有限循环”?

使用Mockito,如何测试“有限循环”

我想测试一种方法,如下所示:

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

而且,我想测试它,以便对“areSearchAreaSuggestionsVisible”的前两个调用返回一个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) 个答案

  1. # 1 楼答案

    只要你把所有存根都变成同一条链的一部分,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