gpt4 book ai didi

java - NotAMockException 而 Mockito.verify(Object,VerificationMode.atleast(2))

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:50:22 26 4
gpt4 key购买 nike

我正在使用Mockito模拟单元测试用例,并且正在获取以下异常(exception)

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type ConsumerImpl and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMetenter code herehod();

我的代码是

 MessageConsumer mConsumer = Mockito.mock(MessageConsumer.class);
String data = "new Message for Testing";
Message message = new Message(data.getBytes());
Mockito.when(mConsumer.next(10, TimeUnit.SECONDS)).thenReturn(message);
StringParserTest parserTest = new StringParserTest();
ConsumerImpl<String> consumer = new ConsumerImpl<String>(mConsumer, parserTest);
String mes=Mockito.verify(consumer,VerificationModeFactory.times(3)).consumeMessage(10,TimeUnit.SECONDS);

请有人帮助我解决这个问题

提前致谢

注册编号

最佳答案

好吧,这正是 mockito 所说的,您没有通过模拟来验证!

ConsumerImpl<String> consumer = new ConsumerImpl<String>(mConsumer, parserTest);
String mes=Mockito.verify(consumer,VerificationModeFactory.times(3)).consumeMessage(10,TimeUnit.SECONDS);

此外,如果您验证了一个模拟,为什么要存储您验证的调用结果,这将没有意义,因为消费者被模拟了。验证是验证对作为单元测试对象的协作者的模拟对象的调用。你的情况还不是很清楚。

此外,您永远不会使用您的模拟 mConsumer 实例。

您绝对应该将测试分为 3 个阶段,一个用于夹具,一个用于操作,一个用于验证。使用 BDD 术语来实现这一点,它增强了此代码的测试人员和 future 读者的理解和可读性(并且 Mockito 通过 BDDMockito 在 API 中提供了它们)。

因为我并没有真正从您提供的代码中得到代码试图测试的内容,所以我会想象一些事情。因此,例如,您将编写这种代码(使用 import static):

// given a consumer
MessageConsumer message_consumer = mock(MessageConsumer.class);
String the_message_data = "new Message for Testing";
given(message_consumer.next(10, SECONDS)).willReturn(new Message(the_message_data.getBytes()));

// when calling the client of the customer (which is the unit that is tested)
new MessageProcessor(message_consumer).processAll();

// then verify that consumeMessage is called 3 times
verify(message_consumer, times(3)).consumeMessage(10, SECONDS);

请记住,Mockito 可帮助您专注于对象之间的交互——因为它是面向对象编程中最重要的概念——尤其是被测试者和他肯定会被 mock 的合作者之间的交互。

关于java - NotAMockException 而 Mockito.verify(Object,VerificationMode.atleast(2)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16818772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com