【问题标题】:Spring Kafka ProducerRecord Mock TestSpring Kafka ProducerRecord 模拟测试
【发布时间】:2021-10-23 17:05:42
【问题描述】:
ProducerRecord<Key,Value> producerRecord = new ProducerRecord<>(topicName, key,value);

ListenableFuture<SendResult<Key,Value>> future = kafkaTemplate.send(producerRecord);

测试用例

@Mock
ProducerRecord<Key,Value> producerRecord;

@Mock
ListenableFuture<SendResult<Key,Value>> future;

@Mock
private KafkaTemplate<Key,Value> producer;

当我模拟发送方法时,它将返回 null 未来对象

when(producer.send(producerRecord)).thenReturn(future);

我找到的解决方案

我通过任何(ProducerRecord.class)所以我会触发你的方法并返回你未来的对象

@Mock
ListenableFuture<SendResult<Key,Value>> future;

@Mock
private KafkaTemplate<Key,Value> producer;

when(producer.send(any(ProducerRecord.class))).thenReturn(future);

【问题讨论】:

    标签: spring spring-boot apache-kafka spring-kafka


    【解决方案1】:

    除了模拟KafkaTemplate#send 方法:

    when(producer.send(producerRecord)).thenReturn(future);
    

    您应该指示您的类夹具实现来初始化模拟对象。它应该是一个预实例步骤,如下所示:

    @BeforeEach
    void setup() {
        MockitoAnnotations.initMocks(this);
    }
    

    将模拟配置(常用配置)也移至设置步骤是一种常见的良好做法:

    @BeforeEach
    void setup() {
        MockitoAnnotations.initMocks(this);
        SendResult<Key,Value> result = Mockito.mock(SendResult.class);
        when(future.get()).thenReturn(result);
        when(producer.send(producerRecord)).thenReturn(future);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 2021-05-28
      • 1970-01-01
      • 2021-05-04
      • 2020-07-07
      • 1970-01-01
      • 2016-06-29
      相关资源
      最近更新 更多