为什么在Mockito.when创建内部调用了该方法?

huangapple go评论72阅读模式
英文:

Why method is invoked inside Mockito.when creation?

问题

以下是您要翻译的内容:

方法 DefaultMessageListenerContainer.isRunning() 被调用在 Mockito.doReturn(..).when() 声明中。为什么?

@Test
public void isRunning_validParams_isOk() {
    DefaultMessageListenerContainer mockMessageListenerContainer = Mockito.mock(DefaultMessageListenerContainer.class);
    List<DefaultMessageListenerContainer> internalState = Arrays.asList();
    Whitebox.setInternalState(this.theService, "jmsListeners", internalState);
    try {
        Mockito
            .doReturn(true)
            .doReturn(false)
            .when(mockMessageListenerContainer.isRunning());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("unexpected exception");
    }
    internalState.add(mockMessageListenerContainer);
    boolean result1 = this.theService.isRunning();
    Assert.assertTrue(result1);
    boolean result2 = this.theService.isRunning();
    Assert.assertFalse(result2);
}
英文:

The method DefaultMessageListenerContainer.isRunning() is called in the Mockito.doReturn(..).when() declaration. Why?

@Test
public void isRunning_validParams_isOk() {
    DefaultMessageListenerContainer mockMessageListenerContainer = Mockito.mock(DefaultMessageListenerContainer.class);
    List&lt;DefaultMessageListenerContainer&gt; internalState = Arrays.asList();
    Whitebox.setInternalState(this.theService, &quot;jmsListeners&quot;, internalState);
    try {
        Mockito
            .doReturn(true)
            .doReturn(false)
            .when(mockMessageListenerContainer.isRunning());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(&quot;unexpected exception&quot;);
    }
    internalState.add(mockMessageListenerContainer);
    boolean result1 = this.theService.isRunning();
    Assert.assertTrue(result1);
    boolean result2 = this.theService.isRunning();
    Assert.assertFalse(result2);
}

答案1

得分: 1

你的代码应该更改为:

.doReturn(false)
.when(mockMessageListenerContainer).isRunning();


---

在使用 `doReturn` 时,`when` 方法期望一个模拟对象,更多信息请参考[文档](https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#doReturn-java.lang.Object-)
英文:

your code should be changed to:

.doReturn(false)
.when(mockMessageListenerContainer).isRunning();

When using doReturn, the when method expects a mock object, more info in the documentation

答案2

得分: 0

问题可能与“isRunning”方法被声明为final有关。

英文:

The problem might be related to the fact that the "isRunning" method is declared as final

huangapple
  • 本文由 发表于 2020年9月23日 16:34:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64024033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定