Spring Boot jupiter 注释自定义扩展配置不起作用

问题描述 投票:0回答:1

我配置了自定义注解:

@Target(allowedTargets = [AnnotationTarget.TYPE, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS])
@Retention(AnnotationRetention.RUNTIME)
@ExtendWith(value = [SpringExtension::class, BuilderTestExtension::class])
@ContextConfiguration(classes = [TestConfig::class])
@SpringBootTest
annotation class BuilderTest

我还配置了 TestConfig:

@ContextConfiguration
@ComponentScan(
    basePackages = ["com.example.api.base.builder"]
)
class TestConfig

BuilderHelper 定义如下,其中 ResponseBuilder 类在

com.example.api.base.builder
包中定义:

@Service
class BuilderHelper(@Autowired var responseBuilder: ResponseBuilder)

到目前为止一切正常。当我尝试为序列化测试创建另一个注释时,例如:

@Target(allowedTargets = [AnnotationTarget.TYPE, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS])
@Retention(AnnotationRetention.RUNTIME)
@ExtendWith(value = [SpringExtension::class, SerializationTestExtension::class])
@ContextConfiguration(classes = [SerializationConfig::class])
@SpringBootTest
annotation class SerializationTest

序列化配置文件定义:

@ContextConfiguration
@ComponentScan(
    basePackageClasses = [ObjectMapper::class]
)
class SerializationConfig

和 SerializationHelper 其中

ObjectMapper
类是包名称为
com.fasterxml.jackson.databind
的外部库:

@Service
class SerializationHelper(@Autowired var objectMapper: ObjectMapper)

现在我的错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected at least 1 bean which qualifies as autowire candidate

我认为是因为配置。我想以某种方式使这 2 个注释或扩展独立。有什么想法吗?

spring-boot kotlin junit5 spring-annotations junit-jupiter
1个回答
0
投票

我觉得你想做的有点过于复杂了。

您可以使用

@TestConfiguration
注释来将您的 testContext 与 applicationContext 完全隔离。

参考:TestConfiguration

我建议你可以这样做:

修改你的

@BuilderTest
注释:

@Target(allowedTargets = [AnnotationTarget.TYPE, AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS])
@Retention(AnnotationRetention.RUNTIME)
@Import(TestConfig::class)
@ExtendWith(SpringExtension::class)
annotation class BuilderTest

如您所见,缺少

@SpringBootTest
注释,因此您可以专门隔离测试类的上下文。此外,您不再需要
@ContextConfiguration
注释。

修改你的测试配置:

@TestConfiguration
class TestConfig {

    @Bean
    fun responseBuilder(): ResponseBuilder {
        // return the instance of ResponseBuilder class here
    }
}

然后在你的测试课上你可以简单地这样做:

@BuilderTest
class ResponseBuilderTest {

    @Autowired
    lateinit var responseBuilder: ResponseBuilder

    @Test
    fun testResponseBuilder() {
        //  your test logic goes here
    }
}

您可以按照此过程对

@SerializationTest
执行相同操作,方法是使用
@TestConfiguration
注释创建一个额外的配置类并为
ObjectMapper
提供实例。

© www.soinside.com 2019 - 2024. All rights reserved.