Spring 使用@SpyBean时未找到定义[SpydeDefinition…的bean

Spring 使用@SpyBean时未找到定义[SpydeDefinition…的bean,spring,kotlin,mockito,integration-testing,spring-kafka,Spring,Kotlin,Mockito,Integration Testing,Spring Kafka,我有一个应用程序,它在@Component中使用@KafkaListener侦听Kafka消息。现在我想使用在后台旋转Kafka的Kafka测试容器进行集成测试。在我的测试中,我想验证侦听器方法是否已调用并完成,但是当我在测试中使用@SpyBean时,我得到: 未找到定义的bean[SpyDefinition@7a939c9ename=,typeToSpy=com.demo.kafka.MessageListener,reset=AFTER] 我正在使用Kotting,重要的课程: 要测试的类

我有一个应用程序,它在@Component中使用@KafkaListener侦听Kafka消息。现在我想使用在后台旋转Kafka的Kafka测试容器进行集成测试。在我的测试中,我想验证侦听器方法是否已调用并完成,但是当我在测试中使用@SpyBean时,我得到:

未找到定义的bean[SpyDefinition@7a939c9ename=,typeToSpy=com.demo.kafka.MessageListener,reset=AFTER]

我正在使用Kotting,重要的课程:

要测试的类

测试班

我感到困惑的原因是,当我将MessageListener添加到MessageListenerTest的@Autowired构造函数时,它确实成功地被注入


为什么测试在使用@SpyBean时找不到bean?

对我来说,使用Java很好:

@春靴测试 SO58184716类应用程序测试{ @间谍 私人倾听者; @试验 无效的test@AutowiredKafkaTemplate模板引发InterruptedException{ template.sendso58184716,foo; CountDownLatch闩锁=新的CountDownLatch1; willAnswerinv->{ inv.callreal方法; 倒数计时; 返回null; }.givensis.listener.listenfo; assertThatlatch.wait10,TimeUnit.SECONDS.isTrue; 验证this.listener.listenfo; } } @SpringBoot应用程序 公共类SO58184716应用程序{ 公共静态无效字符串[]args{ SpringApplication.runSo58184716Application.class,args; } @豆子 公共新话题{ 返回TopicBuilder.nameso58184716.partitions1.replicas1.build; } } @组成部分 类侦听器{ @KafkaListenerid=so58184716,topics=so58184716 在中安装公共无效列表{ System.out.printlin; } }
我刚刚使用IntelliJ将该项目转换为Kotlin,它对我来说仍然很好。嗨,Gary,谢谢你的回答,尽管你的示例略有不同,但它非常有用。这表明它肯定与我的测试设置的bean初始化顺序有关。调查仍在继续:
@Component
class MessageListener(private val someRepository: SomeRepository){

    @KafkaListener
    fun listen(records: List<ConsumerRecord<String, String>>) {
         // do something with someRepository
    }
}
@ExtendWith(SpringExtension::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class KafkaContainerTests {

    // some functionality to spin up kafka testcontainer

}
class MessageListenerTest @Autowired constructor(
        private val someRepository: SomeRepository
) : KafkaContainerTests() {


    @SpyBean
    private lateinit var messageListenerSpy: MessageListener

    private var messageListenerLatch = CountDownLatch(1)

    @BeforeAll
    fun setupLatch() {
        logger.debug("setting up latch")

        doAnswer {
            it.callRealMethod()
            messageListenerLatch.count
        }.whenever(messageListenerSpy).listen(any())
    }

    @Test
    fun testListener(){
        sendKafkaMessage(someValidKafkaMessage)

        // assert that the listen method is being called & finished
        assertTrue(messageListenerLatch.await(20, TimeUnit.SECONDS))
        // and assert someRepository is called
    }
}