【问题标题】:Actually, there were zero interactions with this mock. Embedded Kafka Spring test实际上,与此模拟的交互为零。嵌入式 Kafka Spring 测试
【发布时间】: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


【解决方案1】:

TLDR:不要将@Mock 与@SpringBootTest 一起使用。请改用@MockBean。

您在测试中创建的组件不参与消息处理:

  • 消费者
  • 服务

这源于您使用了@SpringBootTest 注解,它带来了整个应用程序上下文。这意味着 Spring 自己创建所有服务,并愉快地忽略测试中创建的服务。

  • 要替换测试中的 bean,请使用 @MockBean
  • 要将 Spring 创建的 bean 注入到您的测试中,请使用 @Autowired

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2022-01-15
    • 2021-12-14
    相关资源
    最近更新 更多