我正在开发一些使用 Kafka-streams 的应用程序的测试,该应用程序还使用 Spring Boot 1.5,它导入 spring-kafka
的 1.2 版。详细来说,我正在使用 KafkaEmbedded
来避免使用 Kafka 的真实运行实例。
在网上的很多例子中,我发现这种测试的配置使用注解@DirtiesContext
,如下(找到here)
@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
public class SpringKafkaReceiverTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringKafkaReceiverTest.class);
private static String RECEIVER_TOPIC = "receiver.t";
@Autowired
private Receiver receiver;
private KafkaTemplate<String, String> template;
@Autowired
private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;
@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, RECEIVER_TOPIC);
// Rest of tests body
}
我在谷歌上搜索了一下,但找不到使用 @DirtiesContext
的目的。有人可以澄清这一点吗?
非常感谢。
最佳答案
当与@ClassRule
嵌入式kafka一起使用时,@DirtiesContext
不会影响代理;代理通过 @AfterClass
停止。
我们通常建议在类级别使用@DirtiesContext
,因为我们不希望测试框架缓存应用程序上下文,因为它很可能具有 Activity 组件(@KafkaListener
等)。我们希望他们停止,因为代理将在类退出时被杀死。
如果方法被标记为 @DirtiesContext
在这种情况下,它没有任何效果。
如果嵌入式 kafka 被定义为一个 bean 而不是 @ClassRule
,它的生命周期将由应用程序上下文而不是 JUnit 控制。在这种情况下,方法级别 @DirtiesContext
将停止代理以及类级别注释。
关于java - 在单元测试中与 KafkaEmbedded 一起使用时,@DirtiesContext 的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50697440/