Sandy Sandy - 1 year ago 69
Java Question

Overriding @Value in Integration Test

For one of my Spring beans(say Application class), I'm fetching the value of a property( from a properties file( 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,

Application class file:

class Application {
//This value is fetched from properties file
//the value is set to true.
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:

@TestPropertySource(properties = {"spring.main.banner-mode=off", ""})
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", ""})

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download