Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
    }
like image 778
Sandy Avatar asked Jun 19 '17 21:06

Sandy


People also ask

How to override application properties in Spring Boot test?

Overriding a Property File Now we'll override properties by putting the property file in the test resources. This file must be on the same classpath as the default one. This method is very effective when we want to override multiple properties from the file.

How do you override a Spring property?

To override your Spring Boot application properties when it's running on Kubernetes, just set environment variables on the container. To set an environment variable on a container, first, initialise a ConfigMap containing the environment variables that you want to override.

Can we use @value in interface?

No, this is not (directly) possible.

How to override configuration in Spring Boot?

To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.


1 Answers

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.

like image 78
ngreen Avatar answered Oct 24 '22 02:10

ngreen