首页 > 解决方案 > 发现多个@BootstrapWith 声明

问题描述

我正在使用带有这些注释的基本集成测试:

@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [SomeApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DataMongoTest
@EmbeddedKafka(
        partitions = 3,
        controlledShutdown = false,
        brokerProperties = ["listeners=PLAINTEXT://127.0.0.1:9092", "port=9092"])
abstract class IntegrationTestBase {

当我运行测试时,我收到此错误:

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.some.app.application.restapi.DatabaseSetupApiEte]: [@org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.context.SpringBootTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper)]

该错误是由两个注释引起的@SpringBootTest@DataMongoTest包括@BootstrapWith 如下:

@SpringBootTest has @BootstrapWith(SpringBootTestContextBootstrapper.class)

@DataMongoTest has @BootstrapWith(DataMongoTestContextBootstrapper.class)

我需要继续使用@SpringBootTestSpringBootTest.WebEnvironment.RANDOM_PORT但我也想要嵌入式 mongodb@DataMongoTest

有什么建议么?

标签: javaspring-bootkotlin

解决方案


我通过这样做解决了它:

@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [SomeAppApplication::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
abstract class SomeAppSpringBootTest { 

在我希望使用嵌入式 mongodb 的情况下:

@EmbeddedKafka(
        partitions = 3,
        controlledShutdown = false,
        brokerProperties = ["listeners=PLAINTEXT://127.0.0.1:9092", "port=9092"])
abstract class IntegrationTestBase: SomeAppSpringBootTest() {

在上面,您只需包括以下内容即可获得嵌入式 mongodb:

testCompile("de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.2.0") 

在我不希望使用的嵌入式行为的情况下:

@TestPropertySource(properties = ["spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration"])
abstract class EndToEndTestBase: SomeAppSpringBootTest()

因此,对于每种类型的测试,我都使用正确的抽象基测试类。


推荐阅读