在 Guice 中,我有一个带有绑定(bind)的 ProductionModule。在我的测试中,我可以加载该模块以及一个用模拟对象覆盖一些生产绑定(bind)的模块。我如何在 Spring 做这样的事情......
例如,在测试文件中加载 production-spring.xml,然后在 test-spring.xml 中加载测试,这只会覆盖 production-spring.xml 中的一些绑定(bind)
这会测试集成并确保 production-spring.xml 中的更改不会破坏内容。这些是比测试单元更自动化的集成测试,并且工作得非常好。
最佳答案
您可以通过列出多个 xml 文件来覆盖 beans。后面文件中的 Bean 将覆盖之前加载的 Bean。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"classpath:prodDB.xml",
"classpath:applicationContext.xml",
"classpath:testDb.xml"})
public class SpringTest {
@Autowired
protected DataSource dataSource; //uses the datasource from testDb.xml
}
因此,在这种情况下,testDB.xml 会覆盖 prodDb.xml 中配置的数据源。即使您也不使用 SpringJUnit4ClassRunner,这也适用:
new ClassPathXmlApplicationContext(new String[]
{"classpath:prodDb.xml",
"classpath:testDb.xml"});
使用类似 Constretto 的工具您可以对带注释的 bean 执行相同的操作:
@Service
public class FooService...
@Service
@Environment("test")
public class FakeFooService ...
现在,如果您在类上使用 @Environment("test")
注释运行测试,则将使用 FakeFooService。
关于spring - spring 可以对绑定(bind)进行类似 guice 的覆盖吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489274/