0

在我的 web 应用程序中,applicationContext 中有两个数据源 bean,一个用于真实环境,一个用于执行测试。dataSource 对象被注入到一个 DAO 类中。使用 Spring 配置文件我如何配置测试 dataSource 应该在运行测试(JUnit)时注入 DAO 和 real-env dataSource 应该在代码部署到 real-env 时注入 DAO?

4

1 回答 1

1

实际上有两种方法可以实现您的目标:

  1. 一种方法是使用两个不同的 spring 配置文件,一个用于测试(JUnit),另一个用于运行时(real-env)。

用于真实环境:

<!-- default-spring-config.xml -->
<beans>

    ...other beans goes here...

    <bean id="datasource" class="xx.yy.zz.SomeDataSourceProvider1" />

</beans>

用于测试:

<!-- test-spring-config.xml -->
<beans>

    ...other beans goes here...

    <bean id="datasource" class="xx.yy.zz.SomeDataSourceProvider2" />

</beans>

在您的 web.xml中,将default-spring-config.xml指定为spring 在运行时使用的contextConfigLocation :

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/default-spring-config.xml</param-value>
</context-param>

最后在ContextConfiguration中为 Test指定test-spring-config.xml :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/test-spring-config.xml")// it will be loaded from "classpath:/test-spring-config.xml"
public class YourClassTest {

    @Autowired
    private DataSource datasource;

    @Test
    public void your_function_test() {

        //use datasource here...

    }
}

  1. 第二种方法是按照您的建议使用 Spring 配置文件(即使我更喜欢第一种,因为它更适合这种情况)。

首先将这些行添加到您的 web.xml 以让 Spring 了解默认配置文件(real-env):

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>default</param-value
</context-param>

现在在您的 Spring 配置文件(一个配置文件)中创建两个不同的数据源:

<beans xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="...">

    ...other beans goes here...

    <beans profile="default">

        <bean id="defaultDatasource" class="xx.yy.zz.SomeDataSourceProvider1" />

    </beans>

    <beans profile="test" >

        <bean id="testDatasource" class="xx.yy.zz.SomeDataSourceProvider2" />

    </beans>

</beans>

然后使用ActiveProfiles将 DataSource 注入您的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ActiveProfiles("test")
public class YourClassTest {

    @Autowired
    private DataSource datasource;

    @Test
    public void your_function_test() {

        //use datasource here...

    }
}

来源:https ://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles

于 2017-02-10T21:43:54.490 回答