英文:
doNothing on a void method but verify its args
问题
我有一个情景,在这种情况下,我需要一个不执行任何操作的void方法,或者基本上是doNothing()。
但是我仍然希望确保它获得了正确的参数。
根据我尝试的情况,似乎doNothing()实际上并没有执行该方法。
@Test
void whenNoExceptionMetadataAndExceptionThrown_ThenCreateMetadata() throws Exception {
    
    record = new ConsumerRecord<>(topic, partition, offset, partitionKey, bytes);
    doNothing().when(spyProducer)
            .sendMessage(Mockito.any(byte[].class), Mockito.anyString(), Mockito.anyString());
    Whitebox.invokeMethod(kafkaByteArrConsumer, "handleConsumerRecord", record, acknowledgment);
    Mockito.verify(spyProducer, Mockito.times(1))
            .sendMessage(
                    prepareByteArrMsg(new ExceptionMetaData(null, 0, 0, 0), record.value()),
                    partitionKey, topic);
}
这个测试失败了,不是因为参数不匹配,而是因为方法甚至没有被调用。
我通过将所有参数都换成任意匹配器来确认,但仍然没有通过。
我知道解决这个问题的一个方法就是将验证(verify)换成doAnswer(),在其中,如果参数不匹配我会抛出一个异常。但我觉得这不是最佳实践的解决方案...
谢谢
英文:
I have a scenario in which i need a void method to not execute, or doNothing() basically.
But i still want to make sure it got the right arguments.
From what i tried it seems like do the doNothing() actually doesnt execute the method.
 @Test
void whenNoExceptionMetadataAndExceptionThrown_ThenCrateMetadata() throws Exception {
    
    record = new ConsumerRecord<>(topic,partition,offset,partitionKey, bytes);
    doNothing().when(spyProducer)
            .sendMessage(Mockito.any(byte[].class), Mockito.anyString(), Mockito.anyString());
    Whitebox.invokeMethod(kafkaByteArrConsumer, "handleConsumerRecord", record, acknowledgment);
    Mockito.verify(spyProducer, Mockito.times(1))
            .sendMessage(
                    prepareByteArrMsg(new ExceptionMetaData(null, 0, 0, 0), record.value()),
                    partitionKey, topic);
}
this fails, not because the argument isnt matching but because the method was not even invoked.
i confirmed that by swapping all the args to an any matcher and it still didnt pass.
I know one solution to this problem would be just to swap the verify to an doAnswer()
where i throw an exception if the args doesnt match what i need. but i feel like this is not the best practice solution...
Thanks
答案1
得分: 0
好的,这有点尴尬,但实际上问题出在我在我发送的代码片段的完整代码中抛出了错误的异常,一旦我改正了它,它就正常工作了...
我会保留这个问题在这里,因为这是一个使用doNothing并检查其参数的很好的示例。
英文:
Ok, its kind of embarrassing but the problem was actually i threw the wrong exception in the full code of the snippet i sent, once i changed it it worked...
Ill leave this question here cause its a nice example of how to use a doNothing and check its args
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论