21

我们的 Web 应用使用 SystemPropertyPlaceholder 根据系统属性的值加载属性文件(见下文)

在本地运行它的默认设置存储在application.properties. 在生产服务器上,我们目前只是在部署应用程序之前将“env”设置为“production”,它将加载production.properties.

现在为了测试应用程序,test.properties应该使用一个文件。

如果我运行我们的詹金斯构建中的所有测试,添加-Denv=test将按预期工作。但是,如果我只想在 Eclipse 中使用集成的 JUnit 运行器运行单个测试怎么办?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = WebContextLoader.class, locations = {"classpath:application-context.xml" })
public class SomeTest {

有没有办法告诉我的测试它应该在加载 Spring 之前将系统属性“env”设置为“test”?因为 usingMethodInvokingFactoryBean只会在之后出于某种原因设置它,即使我在加载我的属性文件之前设置它:

<bean id="systemPrereqs"
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" value="#{@systemProperties}" />
    <property name="targetMethod" value="putAll" />
    <property name="arguments">
        <!-- The new Properties -->
        <util:properties>
            <prop key="env">test</prop>
        </util:properties>
    </property>
</bean>

<bean
    class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchContextAttributes" value="true" />
    <property name="contextOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:application.properties</value>
            <value>classpath:${env}.properties</value>
            <value>${config}</value>
        </list>
    </property>
</bean>

<bean id="managerDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="username">
        <value>${database.username}</value>
    </property>
    <property name="password">
        <value>${database.password}</value>
    </property>
    <property name="url">
        <value>${database.url}</value>
    </property>

</bean>

使用在 application.properties、production.properties 和 test.properties 中定义的数据库属性。

重点是,当然,我想对所有环境使用相同的上下文文件,否则我可以告诉我的测试使用不同的上下文,我将 PropertyPlaceholder 属性“位置”设置为 test.properties ...但我想要我的测试也涵盖了我的上下文,以便尽早发现任何错误(我正在使用 spring-web-mvc 在我们的 web 应用程序上进行端到端测试,它加载了整个 web 应用程序,在那里提供了一些很好的反馈,并且我不想放弃它)。

到目前为止,我能看到的唯一方法可能是将 JUnit 运行器配置为包含一些系统属性设置参数,尽管我不知道该怎么做..

4

3 回答 3

45

我现在正在解决完全相同的问题,并希望找到方法。您可以调用System.setProperty()测试用例的静态初始化程序。

于 2012-06-12T13:07:06.547 回答
19

在 Eclipse 中,右键单击 JUnit 测试类,选择 Run As > Run Configurations...,然后转到 Arguments 选项卡,在 VM Arguments 下,添加系统属性条目,例如 -Dcatalina.base=C:\programs\ apache-tomcat-7.0.32

于 2012-12-04T05:18:47.470 回答
0

您可以尝试使用depends-on属性让调用 bean 的方法在其他人之前运行

于 2015-02-19T08:22:56.940 回答