【发布时间】:2018-10-18 17:03:39
【问题描述】:
我正在对一个非常简单的 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出现的一样
单元测试的方向是否正确?我怎样才能使测试通过?
亲切的问候。
【问题讨论】:
标签: java apache-kafka mockito