弹簧单元/集成测试设置

时间:2010-02-12 22:09:42

标签: java spring junit log4j

我没有编写单元测试或集成测试,但现在我正在尝试。我很难设置环境。

我在WEB-INF / applicationContext * .xml下有我的应用程序上下文 在我的applicationContext.xml中,它引用了DB用户/传递,LDAP主机等的属性文件

<bean id="propertyConfigurer"
            class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/WEB-INF/spring-config/dev.properties</value>
            </list>
        </property>
    </bean>

我有log4j配置的另一个属性(DEV / Staging / Production的diff配置)。 ${webapp.root}在web.xml中定义

 <!-- log4j setting -->
    <bean id="log4jInitialization" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
        <property name="targetMethod" value="initLogging" />
        <property name="arguments">
            <list>
                <value>${webapp.root}/${log4j.properties.location}</value>
            </list>
        </property>
    </bean>

现在我试图将以下内容放入测试类中。

@Override
protected String[] getConfigLocations() {
   return new String[]{
            "file:trunk/code/web/WEB-INF/applicationContext.xml",
        };
}

这正确引用了我的xml,但所有属性都被搞砸了。

我想知道以下内容:

  • 有没有办法在测试类中正确设置?如果没有,我应该移动这些课程吗?
  • 如果对webroot的引用仅存在于容器中,如何设置Log4j?
  • Spring配置位置的最佳做法是什么?

请告知

由于

3 个答案:

答案 0 :(得分:6)

This blogpost of mine介绍了实现目标的基本步骤。

请注意,单元测试不应该知道您有一个webapp-root - 它们通常在没有启动任何servlet容器的情况下运行。因此,将备用配置文件放在测试包中并尝试。

答案 1 :(得分:1)

对于单元测试,您不应该使用Spring应用程序上下文。您应该单独测试所有的spring bean和控制器,因为它们是系统中的各个单元。因为它们是POJO,所以很容易在测试用例代码中以编程方式将所有内容连接在一起。这也解决了日志属性文件的位置等问题,因为您可以以编程方式指定不依赖于webroot属性的其他路径。

Spring Reference中的testing chapter提供了如何处理使用Spring的应用程序的单元和集成测试的良好概述。它还提供了Spring提供的各种支持类的详细信息,以帮助编写单元和集成测试。

答案 2 :(得分:1)

您可以使用注释从测试中引用必要的配置,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
     DependencyInjectionTestExecutionListener.class,
     DirtiesContextTestExecutionListener.class,
     TransactionalTestExecutionListener.class })
@ContextConfiguration(locations = {
     "file:../WebService/src/main/resources/application-context.xml",
     "file:../ServiceLayer/src/test/resources/ServiceLayer-dao-test-context.xml" })
public class MyTest {
     // class body...
}