用KafkaProducer和ProducerRecord进行Mockito.verify

时间:2018-10-18 07:39:13

标签: java apache-kafka mockito

我正在为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的键不相同,值看起来相同

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

亲切的问候。

2 个答案:

答案 0 :(得分:1)

此代码:

verify(mockKafkaProducer).send(
        new ProducerRecord<>(
            topic,
            Transformer.HexStringToByteArray(id),
            mockedEntity.serialize()
        )
    );

手段:
“验证使用以下参数在' mockKafkaProducer '上调用了<< em> send ”:

此断言失败,因为send实际上是用不同的参数调用的。

答案 1 :(得分:1)

我建议捕获参数并进行验证。请参见下面的代码:

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

这更具可读性(我的观点),是该方法所发生情况的一种证明文件