【问题标题】:@SpringBootTest annotation on interfrace not working接口上的@SpringBootTest 注释不起作用
【发布时间】:2018-05-13 09:37:21
【问题描述】:

目前无法将注解SpringBootTest 放在接口上,从接口继承并运行测试。

@ExtendWith(SpringExtension::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
interface SpringBootTestBase

class GreetingControllerITest : SpringBootTestBase {

    @Autowired
    private lateinit var restTemplate: TestRestTemplate

    @Test
    fun `spring boot endpoint gets correct greeting`() {
        val body = restTemplate.getForObject("/greet/World", String::class.java)
        assertThat(body).isEqualTo("Hello, World!")
    }
}

NPE 失败

Caused by: java.lang.NullPointerException: null
    at org.springframework.boot.test.context.SpringBootTestContextCustomizer.customizeContext(SpringBootTestContextCustomizer.java:50) ~[spring-boot-test-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.boot.test.context.SpringBootContextLoader$ContextCustomizerAdapter.initialize(SpringBootContextLoader.java:326) ~[spring-boot-test-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.boot.SpringApplication.applyInitializers(SpringApplication.java:625) ~[spring-boot-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.boot.SpringApplication.prepareContext(SpringApplication.java:365) ~[spring-boot-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:325) ~[spring-boot-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:138) ~[spring-boot-test-2.0.0.M6.jar:2.0.0.M6]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) ~[spring-test-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ~[spring-test-5.0.1.RELEASE.jar:5.0.1.RELEASE]
    ... 61 common frames omitted

这个接口的原因是,把所有的注解放在接口上,让我们所有的测试都从那个接口继承 -> 避免注解代码重复

使用基类代替接口对我来说不是真正的选择,因为我有其他基类要继承,它们与测试无关。

这是我应该为 Spring 社区带来的有用功能吗?

【问题讨论】:

    标签: spring spring-test junit5


    【解决方案1】:

    没错:Spring Boot 目前没有在接口上搜索与测试相关的注解。

    如果您觉得这很有用,请为 Spring Boot 打开一个GitHub issue

    另一方面,如果您的主要目标是避免注解重复,那么这已经得到支持,因为核心 Spring 和 JUnit Jupiter 都支持组合注解

    有关结合 Spring、Spring Boot 和 JUnit Jupiter 注解的具体示例,请查看我的 spring-events 示例项目中的 @SpringEventsWebTest 注解。

    问候,

    Sam(Spring TestContext Framework 的作者和核心 JUnit 5 提交者)

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2020-10-09
      • 2012-09-19
      • 2015-09-14
      • 2017-08-20
      相关资源
      最近更新 更多