[英]Mockito.verify with KafkaProducer and ProducerRecord
我正在為KafkaProducer的一個非常簡單的包裝器類進行單元測試,該包裝器的send方法就是這樣
public class EntityProducer {
private final KafkaProducer<byte[], byte[]> kafkaProducer;
private final String topic;
EntityProducer(KafkaProducer<byte[], byte[]> kafkaProducer, String topic)
{
this.kafkaProducer = kafkaProducer;
this.topic = topic;
}
public void send(String id, BusinessEntity entity) throws Exception
{
ProducerRecord<byte[], byte[]> record = new ProducerRecord<>(
this.topic,
Transformer.HexStringToByteArray(id),
entity.serialize()
);
kafkaProducer.send(record);
kafkaProducer.flush();
}
}
單元測試的內容如下:
@Test public void send() throws Exception
{
@SuppressWarnings("unchecked")
KafkaProducer<byte[], byte[]> mockKafkaProducer = Mockito.mock(KafkaProducer.class);
String topic = "mock topic";
EntityProducer producer = new EntityProducer(mockKafkaProducer, topic);
BusinessEntitiy mockedEntity = Mockito.mock(BusinessEntity.class);
byte[] serialized = new byte[]{1,2,3};
when(mockedCipMsg.serialize()).thenReturn(serialized);
String id = "B441B675-294E-4C25-A4B1-122CD3A60DD2";
producer.send(id, mockedEntity);
verify(mockKafkaProducer).send(
new ProducerRecord<>(
topic,
Transformer.HexStringToByteArray(id),
mockedEntity.serialize()
)
);
verify(mockKafkaProducer).flush();
第一種驗證方法失敗,因此測試失敗,並顯示以下消息:
Argument(s) are different! Wanted:
kafkaProducer.send(
ProducerRecord(topic=mock topic, partition=null, key=[B@181e731e, value=[B@35645047, timestamp=null)
);
-> at xxx.EntityProducerTest.send(EntityProducerTest.java:33)
Actual invocation has different arguments:
kafkaProducer.send(
ProducerRecord(topic=mock topic, partition=null, key=[B@6f44a157, value=[B@35645047, timestamp=null)
);
最相關的是ProducerRecord的鍵不相同,值看起來相同
單元測試的方向是否正確? 我怎樣才能通過考試?
親切的問候。
這段代碼:
verify(mockKafkaProducer).send(
new ProducerRecord<>(
topic,
Transformer.HexStringToByteArray(id),
mockedEntity.serialize()
)
);
手段:
“確認‘ 發送 ’被稱為在‘mockKafkaProducer’使用以下參數:......”
該聲明失敗,因為實際上使用不同的參數調用了send。
我建議捕獲論點並進行驗證。 請參見下面的代碼:
ArgumentCaptor<ProducerRecord> captor = ArgumentCaptor.forClass(ProducerRecord.class);
verify(mockKafkaProducer).send(captor.capture());
ProducerRecord actualRecord = captor.getValue();
assertThat(actualRecord.topic()).isEqualTo("mock topic");
assertThat(actualRecord.key()).isEqualTo("...");
...
這更具可讀性(我的觀點),是該方法正在發生的一種文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.