mockito.verify与kafkaproducer和producerrecord

a64a0gku  于 2021-06-06  发布在  Kafka
关注(0)|答案(2)|浏览(313)

我正在为一个kafkaproducer单元测试一个非常简单的 Package 类,其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的键不相同,值看起来相同
单元测试的方向是否正确?我怎样才能通过考试?
谨致问候。

k4aesqcs

k4aesqcs1#

我建议抓住这个论点并加以验证。请参见下面的代码:

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

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

sczxawaw

sczxawaw2#

此代码:

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

指:
“验证是否使用以下参数对”“mockkafkaproducer”“调用了”“send”“:”
这个Assert失败,因为send实际上是用不同的参数调用的。

相关问题