2017-06-19 41 views
1

对于我的其中一个Spring bean(称为Application类),我从属性文件(prop.properties)中获取属性值(my.property.flag = true/false)使用@Value注释。这很好。在集成测试中重写@Value

我需要编写一个集成测试(比如说ApplicationIt类),在这里我需要测试属性的值,例如true和false。

在我的属性文件中,该属性的值设置为true。是否可以从我的集成测试中动态地将该值设置为false?

例如

prop.properties:

my.property.flag=true 

应用的类文件:

@Component 
    class Application { 
     //This value is fetched from properties file 
     //the value is set to true. 
     @Value(${my.property.flag}) 
     private String isTrue; 
     ...... 
     .......... 
    } 

集成测试:

class ApplicationIT { 
     //how can I set the value of isTrue here to false? 
    } 
+0

您可以创建一个单独的属性与测试忽略文件将其更改为任何你想要的值。 – shmosel

+0

此属性文件中有许多属性,并且我拥有的要求仅适用于单个属性。我不认为它足够明智地为这个单独的属性创建一个新的属性文件。 – Sandy

+0

你可能要检查这个https://stackoverflow.com/questions/16478679/update-field-annotated-with-value-in-runtime –

回答

4

您可以按如下方式指定的测试类测试属性:

@RunWith(SpringRunner.class) 
@TestPropertySource(properties = {"spring.main.banner-mode=off", "my.property.flag=false"}) 
public class MyTest { 

由于Spring有属性覆盖的整个层次,这工作得很好,不足之处被你需要单独的测试类不同的值。如果您使用的是Spring Boot,还有另一个注释提供了相同的功能,但也有更多的配置测试环境的选项。例如:

@SpringBootTest(properties = {"spring.main.banner-mode=off", "my.property.flag=false"}) 

同样,您将需要单独的测试类来处理硬编码的测试属性。

0

优选地,使用构造器注入代替字段注射:

@Component 
class Application { 

    Application(@Value("${my.property.flag}") boolean flag) { 
     ... 
    } 
} 

这使得使用嘲笑或测试值作为传递一个参数一样简单。

1

我想提一下很好的旧反射方式。你可以使用Spring提供的实用工具类它,你在你的组件接线完毕后:

ReflectionTestUtils.setField(component, "isTrue", true) 

可以在随后的测试中