尝试使用 Mockito 为下面的代码编写单元测试,但我得到了误用方法异常。结果不为空,已验证,也进入循环。
if(Result!=null) {
result.getRecordMetadata().topic()
}
这是我写的:
@Mock
private SendResult<String, data> sendResultData;
RecordMetadata recordMetadata = new RecordMetadata(new TopicPartition("topic", 0), 0, 0, 1234567890L, 1234567890L, 1024, 1024);
SendResult<String, Data> result = new SendResult<String, Data>(producerRecord, recordMetadata);
when(recordMetadata.topic()).thenReturn("topic");
when(sendResultData.getRecordMetadata()).thenReturn(recordMetadata);
例外:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
you stub either of: final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
inside when() you don't call method on mock but on some other object.
at XXXXX.test(Test.java:172)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
Mockito无法模拟/监视最终课程。RecordMetadata 是最后一个类。
您可以做的是:因为
Future<RecordMetadata
>
在 Kafka 上执行发送时返回。
- 模拟返回的内容(结果未来(
未来未来 = Mockito.mock(未来.class(;
- 创建/实例化虚拟记录元数据,如下所示
TopicPartition topicPartition = new TopicPartition("test",1); RecordMetadata metadata = new RecordMetadata(topicPartition, 0,0,0,Long.valueOf(0),0, 0);
- 然后,每当您对返回的结果进行获取时(步骤 1(,使模拟的未来返回您在步骤 2 中创建的虚拟记录元数据。
when(future.get(((.thenReturn(metadata(;
我没有看到你在示例中的任何地方嘲笑recordMetadata
。你不能模拟一个不是模拟或间谍的对象的方法。
您应该提供带有注释的模拟:
@Mock
private RecordMetadata recordMetadata;
或者简单地:
RecordMetadata recordMetadata = Mockito.mock(RecordMetadata.class);
此外,@mock
注释应@Mock