如何在没有参数的情况下使用Mockito.doAnswer()处理void方法?

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

How to use Mockito.doAnswer() with a void method with no parameters?

问题

@Test
public void successfulHandshake(){
    HandshakeImpl1Server handShake = new HandshakeImpl1Server();
    handShake.setHttpStatus((short) 101);

    authUnderTest.authenticate(callback);

    doAnswer(invocation -> {
        websocket.onOpen(handShake);
        return null;
    }).when(websocket).open();
    
    verify(websocket, times(1)).send(any(String.class));
}

doAnswer 永远没有被调用有什么想法吗
英文:
@Test
public void successfulHandshake(){
    HandshakeImpl1Server handShake = new HandshakeImpl1Server();
    handShake.setHttpStatus((short) 101);

    authUnderTest.authenticate(callback);

    doAnswer(invocation -> {
        websocket.onOpen(handShake);
        return null;
    }).when(websocket).open();
    
    verify(websocket,times(1)).send(any(String.class));
}

doAnswer is never called. Any ideas?

答案1

得分: 1

你需要在调用被测试方法之前进行方法存根,而不是之后。

在调用 authUnderTest.authenticate 之前移动 doAnswer。

英文:

You need to stub your methods before, not after call to method under test.

Move doAnswer before call to authUnderTest.authenticate

huangapple
  • 本文由 发表于 2020年9月10日 02:14:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63817330.html
匿名

发表评论

匿名网友

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

确定