我们的 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 运行器配置为包含一些系统属性设置参数,尽管我不知道该怎么做..