【发布时间】:2021-06-13 11:08:40
【问题描述】:
我正在尝试查看当消费者使用来自 Kafka 主题的消息时是否调用了 Service 类中的方法,但我得到的错误是与 Mock 没有零交互。当测试运行时,它会消耗消息,我可以在终端上看到服务方法实际上被调用(我尝试使用打印),但它没有通过测试。
我的消费者类:
@Component
public class Consumer {
@Autowired
private Service service;
@KafkaListener(topics = "topic")
public void consume(String message) {
service.add();
}
}
测试:
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
@DirtiesContext
@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9092", "port=9092" })
class ConsumerTest {
@Mock( lenient = true)
private Service service;
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@InjectMocks
private Consumer consumer;
@Test
public void givenEmbeddedKafkaBroker_whenExistsTemperatureMessageInTopic_thenMessageReceivedByConsumerAndServiceInvoked()
throws Exception {
String message = "Hello";
kafkaTemplate.send("topic", message);
Mockito.verify(service, times(1)).add();
}
}
【问题讨论】:
-
您的消费者类有一个服务字段,在测试期间您永远不会将模拟的服务实例传递给它
-
我需要如何通过它?
-
与其使用
InjectMocks,不如在您的消费者类中创建一个接受服务的构造函数 -
您还需要在测试中实际使用消费者
标签: spring unit-testing testing mockito