Java 如何在单元(或集成)测试中注入@值而不写出临时文件
我们有一个基于Spring的项目,其单元测试创建临时属性文件,以发送到应用程序上下文中,如:Java 如何在单元(或集成)测试中注入@值而不写出临时文件,java,spring,Java,Spring,我们有一个基于Spring的项目,其单元测试创建临时属性文件,以发送到应用程序上下文中,如: AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(PropertyPlaceholderConfigurer.class); PropertyPlaceholderConfigu
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(PropertyPlaceholderConfigurer.class);
PropertyPlaceholderConfigurer propertyConfigurer = applicationContext.getBean(PropertyPlaceholderConfigurer.class);
propertyConfigurer.setLocation(new DefaultResourceLoader().getResource("file:" + file.getAbsolutePath()));
除了写出临时文件然后以这种方式读取之外,还有更好的方法发送一组属性(作为@Value
s注入)吗
显然,我希望属性只在测试期间有效,因此将它们塞进
System.properties
可能不合适 这只是部分答案,但:
显然,我希望这些属性只在
测试,所以将它们塞进System.properties可能不是
合适
Maven和Ant都可以在不同的fork模式下运行Junit。如果您选择每个测试,
,则将为每个测试启动一个新的VM,但上述情况不适用
我并不是说你应该这么做,只是试着让图片完整:-)没错,这很有帮助,尽管它也会减慢测试套件的速度(如果我没记错的话)。不过,可能必须这样做。你能提供更多细节吗。您是否也在尝试动态设置属性文件名?你能利用类路径或测试类名来帮助你吗?我有
@Component
s,它们有@Value
注入,我想为每个测试运行设置值;我继承的代码为此使用了临时文件,但我想知道是否有更直接的方法。