【发布时间】:2018-04-04 02:14:14
【问题描述】:
如何以惯用的方式覆盖 Spring(Boot)集成测试中的 bean?
到目前为止,我的源配置是这样的:
@Configuration
class ApplicationConfiguration {
@Bean
CarsRepository carsRepository() {
// return some real sql db
}
}
还有这样的测试:
@SpringBootTest
class ApplicationISpec extends Specification {
@Configuration
@Import(Application.class)
static class TestConfig {
@Bean
@Primary
CarsRepository testsCarsRepository() {
// return some in-memory repository
}
}
def "it can do stuff with cars"() {
// do some REST requests to application and verify it works
// there is no need to make real calls to real DB
}
}
第一件事是测试 bean testsCarsRepository 方法必须不同于原始方法(这并不明显,并且没有警告/错误)。
但最后一个问题是:在集成测试中用 Spring 覆盖 bean 的惯用方式是什么?
当我在 Twitter - Stephane Nicoll 上发布有关方法名称的 WTF 时,说 @Primary 不打算用于在测试中覆盖 bean。
那么首选的方法是什么?
【问题讨论】:
-
@MockBean看起来不错。 -
@StephaneNicoll 我已经编辑了帖子,所以它更多地说明了用例。我不想嘲笑我的豆子。而不是我只想用其他一些测试实现替换它。想象一下,我想运行 Spring 集成测试(因此所有 bean 图都已加载),但我想用内存中的实现替换一些边界 bean(如 DB、外部服务等)
-
您所指的是我们创建
MockBean的原因。如果您想使用内存数据库运行,我们也支持 (@AutoconfigureTestDatabase)。在不使用配置文件的情况下覆盖 bean 需要订购和使用相同的 bean 名称,因此它有点脆弱。所以我会在拒绝之前先看看这些选项。 -
@StephaneNicoll 感谢您的意见。所以可能
@Profile和@Primary是我要走的路。我想用测试 bean 替换应用程序 bean。它不必与数据库相关。它可以有一些配置选项,或者类似的东西。我不想嘲笑它。我只想使用不同的实现进行测试。感谢贡献! -
你不需要
@Primary。接受的答案对我来说似乎有点好
标签: spring spring-boot spring-boot-test