gpt4 book ai didi

java - Mockito.verify 使用 KafkaProducer 和 ProducerRecord

转载 作者:行者123 更新时间:2023-11-30 02:00:56 30 4
gpt4 key购买 nike

我正在对 KafkaProducer 的一个非常简单的包装类进行单元测试,其发送方法就像这样

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的key不一样,value看起来一样

单元测试的方向是否正确?我怎样才能通过测试?

亲切的问候。

最佳答案

我建议捕获该论点并验证它。请看下面的代码:

    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("...");
...

这更具可读性(我的观点),它是方法中发生的事情的文档

关于java - Mockito.verify 使用 KafkaProducer 和 ProducerRecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52869183/

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