我最近找到了一个解决方案,可以让我为我的单元测试加载系统属性。如果我单独运行测试,它会很好,但如果我选择运行整个测试套件,它会失败。有人能告诉我为什么吗?
第一步是加载测试应用程序上下文:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
下一步是创建一个将加载系统属性的类:
import java.io.InputStream;
import java.util.Properties;
import javax.annotation.PostConstruct;
import org.springframework.core.io.Resource;
public class SystemPropertiesLoader{
private Resource resource;
public void setResource(final Resource resource){
this.resource = resource;
}
@PostConstruct
public void applyProperties() throws Exception{
final Properties systemProperties = System.getProperties();
final InputStream inputStream = resource.getInputStream();
try{
systemProperties.load(inputStream);
} finally{
inputStream.close();
}
}
}
最后一步是在我的测试应用程序上下文中将其列为 bean:
<bean class="com.foo.SystemPropertiesLoader">
<property name="resource" value="classpath:localdevelopment_Company.properties" />
</bean>
当我运行测试套件时,我的几个测试都失败了,所有这些测试都依赖于系统属性。如果我去特定的测试并运行它,它就会通过。我已经对其进行了调试,并且验证了 SystemPropertiesLoader 中的代码正在执行,并且所有其他 bean 都已成功从上下文中拉出。但是,这些属性没有被正确加载,因为当我尝试访问它们时它们都为空。有什么建议么?