【发布时间】:2012-06-15 08:43:21
【问题描述】:
我们的网络应用使用 SystemPropertyPlaceholder 根据系统属性的值加载属性文件(见下文)
在本地运行它的默认设置存储在application.properties。在生产服务器上,我们目前只是在部署应用之前将“env”设置为“production”,它将加载 production.properties。
现在应该使用test.properties 文件来测试应用程序。
如果我运行我们的 jenkins 构建中的所有测试,添加 -Denv=test 将按预期工作。但是,如果我只想在 Eclipse 中使用集成的 JUnit 运行器运行单个测试呢?
@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 属性“位置”设置为 test.properties...但我希望我的测试也涵盖我的上下文,以便尽早发现任何错误(我正在使用 spring-web-mvc 在我们的 Web 应用程序上进行端到端测试,它加载了整个 Web 应用程序,提供了一些不错的那里有反馈,我不想放弃它)。
到目前为止,我能看到的唯一方法可能是将 JUnit 运行器配置为包含一些系统属性设置参数,尽管我不知道该怎么做..
【问题讨论】:
-
我会说在这些配置文件中使用配置文件会导入您需要的正确文件。看起来你正在重新发明轮子。使用配置文件,您只需将
@ActiveProfiles添加到您的测试用例中即可加载正确的内容。代替 od-Denv=test然后您将使用-Dspring.active.profiles=test
标签: java eclipse spring junit system-properties