如何禁用 @KafkaListener 示例 @SpringBootTest 使用Spring Boot(2.2+)和SpringKafka(2.4+)进行测试?目标是在特定测试中禁用kafka监听器,这样这些测试就可以在不启动嵌入式kafka代理的情况下运行。
@KafkaListener
@SpringBootTest
egdjgwm81#
springboot允许通过创建自定义的 TypeExcludeFilter .若要禁用kafka侦听器,请排除所有具有用注解的方法的类 @KafkaListener 或者 @KafkaHandler :
TypeExcludeFilter
@KafkaHandler
public class KafkaListenersTypeExcludeFilter extends TypeExcludeFilter { private static final String KAFKA_LISTENER = "org.springframework.kafka.annotation.KafkaListener"; private static final String KAFKA_HANDLER = "org.springframework.kafka.annotation.KafkaHandler"; @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) { AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); return annotationMetadata.hasAnnotatedMethods(KAFKA_LISTENER) || annotationMetadata.hasAnnotatedMethods(KAFKA_HANDLER); } @Override public boolean equals(Object o) { return o != null && getClass() == o.getClass(); } @Override public int hashCode() { return 1; } }
用注解说明Spring启动测试 @TypeExcludeFilters 与 KafkaListenersTypeExcludeFilter 作为一个值:
@TypeExcludeFilters
KafkaListenersTypeExcludeFilter
@RunWith(SpringRunner.class) @SpringBootTest @TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class) public class SampleSpringBootTest { //... }
带注解的Spring Boot测试 @TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class) 不会启动Kafka侦听器,因此不需要Kafka代理。当只有几个kafka监听器bean时,您还可以按照注解中建议的死区来模拟监听器bean
@TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class)
@RunWith(SpringRunner.class) @SpringBootTest @MockBean({ SampleKafkaListener.class }) public class SampleSpringBootTest { //... }
1条答案
按热度按时间egdjgwm81#
springboot允许通过创建自定义的
TypeExcludeFilter
.若要禁用kafka侦听器,请排除所有具有用注解的方法的类
@KafkaListener
或者@KafkaHandler
:用注解说明Spring启动测试
@TypeExcludeFilters
与KafkaListenersTypeExcludeFilter
作为一个值:带注解的Spring Boot测试
@TypeExcludeFilters(KafkaListenersTypeExcludeFilter.class)
不会启动Kafka侦听器,因此不需要Kafka代理。当只有几个kafka监听器bean时,您还可以按照注解中建议的死区来模拟监听器bean