我有一个支持多个数据库的应用程序(MySQL,Oracle,SQL Server,Postgre)。我想在Spring中配置多个配置文件以在多个数据库上运行单元测试(我使用H2作为我的主内存数据库)。每当我通过maven运行构建时,它将在多个数据库上运行所有单元测试。目前,我每次使用maven构建项目时都可以在一个数据库上运行单元测试。我如何配置来实现这一目标?
答案 0 :(得分:1)
我会使用自定义JUnit规则:
public class MultipleSpringConfigRule implements TestRule
{
private Object _testObject;
private String[] _configLocations;
public MultipleSpringConfigRule(Object testObject, String... configLocations)
{
_testObject = testObject;
_configLocations = configLocations;
}
public Statement apply(final Statement base, Description description)
{
return new Statement()
{
@Override
public void evaulate() throws Throwable
{
for (String configLocation : _configLocations)
{
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext(configLocation);
context.getAutowireCapableBeanFactory().autowireBean(_target);
context.start();
try
{
// executes Before methods, current Test method, and After
// methods.
base.evaluate();
} finally
{
context.close();
}
}
}
};
}
}
将规则添加到需要针对多个弹簧配置运行的任何测试类:
public class MyTests
{
@Rule
public MultipleSpringConfigRule _myRule = new MultipleSpringConfigRule(
this,
"path/to/mysql/config.xml",
"path/to/oracle/config.xml",
"path/to/sqlserver/config.xml",
"path/to/postgre/config.xml");
@Autowired
private MyRepository _myRepository;
...
}