【发布时间】: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