首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Spring和H2在多个数据库上运行单元测试

问使用Spring和H2在多个数据库上运行单元测试
EN

Stack Overflow用户
提问于 2014-01-19 00:48:03
回答 1查看 142关注 0票数 0

我有一个支持多个数据库(MySQL、Oracle、Server、Postgre)的应用程序。我想在Spring中配置多个配置文件,以便在多个数据库上运行单元测试(我使用H2作为我的主内存数据库)。每当我通过maven运行build时,它就会在多个数据库上运行所有单元测试。目前,每当我通过maven构建项目时,我就只能在一个数据库上运行单元测试。如何配置来实现这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-19 01:22:18

我将使用自定义的JUnit规则:

代码语言:javascript
复制
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();
                    }
                }
            }
        };
    }
}

将规则添加到任何需要针对多个spring配置运行的测试类:

代码语言:javascript
复制
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;

    ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21211835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档