Sandy Sandy - 4 months ago 14
Java Question

Overriding @Value in Integration Test

For one of my Spring beans(say Application class), I'm fetching the value of a property(my.property.flag=true/false) from a properties file(prop.properties) using @Value annotation. That works perfectly fine.

I need to write an integration test(say ApplicationIt class) where I need to test with both the values of the property i.e. for both true and false.

In my properties file, the value of the property is set to true. Is it possible to set the value dynamically to false from my Integration test?

For Example,

prop.properties:

my.property.flag=true


Application class file:

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


Integration Test:

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

Answer Source

You can specify test properties on the test class as follows:

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

Since Spring has a whole hierarchy of property overrides, this works pretty well, the downside being you need separate test classes for different values. If you're using Spring Boot, there's another annotation that provides the same functionality but also has more options for configuring your test environment. Example:

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

Again, you will need separate test classes to handle hard-coded test properties.