现在不可能将注释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
这个接口的原因是,将所有注释放在接口上,让我们的所有测试从那个->继承,避免注释-代码复制。
使用基类而不是接口对我来说不是真正的选择,因为我还有其他基类要继承,它们与测试无关。
这是否是我应该为春季社区带来的一个有用的特性呢?
发布于 2017-11-30 13:11:31
这是正确的: Spring目前并不在接口上搜索与测试相关的注释。
如果您认为这是有用的,那么请为Spring打开一个GitHub问题。
另一方面,如果您的主要目标是避免注释重复,那么这已经被支持,因为核心Spring和JUnit木星都支持组合注释。
关于将Spring、Spring和JUnit木星注释结合在一起的具体示例,请查看我的春季活动示例项目中的@SpringEventsWebTest
注释。
致以敬意,
Sam ( Spring TestContext框架和核心JUnit 5提交器的作者)
https://stackoverflow.com/questions/47556830
复制相似问题