Man*_*nza 5 spring spring-test spring-boot
故事是这样的:每次我想运行一个或多个集成测试时,Spring 上下文都需要启动,最多需要 2 分钟。
这有点令人沮丧,因为每次最小的更改之后我都需要等待以检查测试结果。
有没有办法在测试结束后保持 Spring 上下文运行,以避免等待?类似于启动 Spring 应用程序一次然后执行测试。
更新
刚刚发现了一个非常相似的问题: 如何在 Intellij Idea 中的测试运行之间保持 spring 上下文加载?
为了完整起见,复制我在另一个问题中的答案:
可能不是最干净的解决方案,但效果很好。
// In a different package from the main application
// The `scanBasePackages` is the same as the main application!
@SpringBootApplication(scanBasePackages = ["com.example.api"])
class TestApplication {
companion object {
@JvmStatic // main method to be able to run it in IDEs
fun main(args: Array<String>) {
runApplication<TestApplication>(*args)
}
}
}
Run Code Online (Sandbox Code Playgroud)
// In a different package from to the above
// Ideally this should almost exclude every Spring configurations
// in the classpath (they should be loaded in the above application)
@SpringBootApplication
class TestApplicationLoader {
@Value("\${test-subject.context.load:true}")
private var loadContext = false
@Bean
fun testSubject(): Closeable {
return if (loadContext) {
val environment = StandardEnvironment()
val sa = SpringApplication(TestApplication::class.java)
sa.run()
} else { // it's loaded by the IDE or Gradle!
Closeable {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
// If you make TestApplicationLoader as thin as possible
// this should take around one second or two to complete!
@SpringBootTest(classes = [TestApplicationLoader::class])
class MyControllerTest : StringSpec() {
override fun extensions() = listOf(SpringExtension)
@Autowired
lateinit var testRestTemplate: TestRestTemplate
init {
"test" {
val res = testRestTemplate.getForObject("http://localhost:8081/hello", String::class.java)
res shouldBe "mocked in test-application"
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法有一些需要注意/改进的地方:
我在这里创建了一个示例项目作为概念证明。
(事实上,没有人处理过这个问题,这真是令人难以置信。期待官方和/或更好的解决方案)
| 归档时间: |
|
| 查看次数: |
408 次 |
| 最近记录: |