使用 Mockito,如何使用布尔条件测试“有限循环"? [英] Using Mockito, how do I test a 'finite loop' with a boolean condition?

查看:14
本文介绍了使用 Mockito,如何使用布尔条件测试“有限循环"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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"的前 2 次调用返回 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆