我已经进行了几次繁重的Spring集成测试(是的,这不是最好的方法,并且我没有足够的时间来正确地模拟所有外部dep)
这是测试的典型注释
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
@EmbeddedKafka(
partitions = 1,
brokerProperties = {"log.dir=target/${random.int}/embedded-kafka/data"},
topics = {
"${service.topic}",
"${service.dead-letter-topic}"
})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OneOfMyHeavyintegrationTests extends DatabaseBackedTest {
// omitted for brevity
//
}
// foundation for DB in tests
@ContextConfiguration(initializers = DatabaseBackedTest.Initializer.class)
public abstract class DatabaseBackedTest {
private static final EmbeddedPostgresInfo db = EmbeddedPostgresDatabase.create().start();
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext context) {
TestPropertyValues.of("spring.datasource.url=" + db.getJdbcUrl()).applyTo(context.getEnvironment());
}
}
}
由于以下原因,测试会定期失败
22:14:51.462 [main] INFO o.a.k.common.utils.AppInfoParser - Kafka version : 2.0.1
22:14:51.463 [main] INFO o.a.k.common.utils.AppInfoParser - Kafka commitId : fa14705e51bd2ce5
22:14:51.466 [main] WARN o.a.k.common.utils.AppInfoParser - Error registering AppInfo mbean
javax.management.InstanceAlreadyExistsException: kafka.server:type=app-info,id=0
at java.management/com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:436)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1855)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:955)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:890)
at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:320)
at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522)
at org.apache.kafka.common.utils.AppInfoParser.registerAppInfo(AppInfoParser.java:62)
at kafka.server.KafkaServer.startup(KafkaServer.scala:321)
at kafka.utils.TestUtils$.createServer(TestUtils.scala:132)
at kafka.utils.TestUtils.createServer(TestUtils.scala)
有两个问题:
1.使测试共存的正确方法是什么?我在surefire插件中设置了forkCount=0
。似乎有帮助
mock
/ disable
组件? 2.1。我真的不需要在每次测试时都开始我所有的@Scheduled
@Component
2.2。我真的不需要在每次测试时都开始接触Kafka消费者
谢谢!
答案 0 :(得分:1)
如果要使用kafka运行多个测试,可以在测试类上使用DirtiesContext批注。这将告诉春天,该测试所做的事情可能会与其他对象发生冲突,需要清理。您应该将其放在使用kafka的每个类上(出现此错误)
如果您的系统组件在这些测试中不需要使用,请在服务器启动时使用MockBean批注将其替换为模拟