设置 JUnit Runner (Eclipse) 的系统属性以测试 Spring Web App

2022-09-02 02:21:09

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

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

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

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

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

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

<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 属性“location”设置为 test.properties...但是我希望我的测试也覆盖我的上下文,以便尽早发现任何错误(我正在使用spring-web-mvc在我们的Web应用程序上进行端到端测试,它加载了整个Web应用程序,在那里提供了一些很好的反馈,我不想失去它)。

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


答案 1

我现在正在研究完全相同的问题,并希望找到方法。可以调用测试用例的静态初始值设定项。System.setProperty()


答案 2

在 Eclipse 中,右键单击 JUnit 测试类,选择“运行方式>运行配置...”,然后转到“参数”选项卡,然后在“VM 参数”下添加系统属性条目,例如 -Dcatalina.base=C:\programs\apache-tomcat-7.0.32


推荐