Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can load application.properties into test class for getting the spring.profiles.active value?

I'm writing integration test which should works only with the specific profile. The problem is that I should get profile name from spring.profiles.active value in application.properties file. But I always get null due to real value from application.properties.

I've created for main method which explicitly put value into System.properties:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
}
    @Autowired
   public MyApplication(Environment environment) {
      String property = "spring.profiles.active";
      System.getProperties().setProperty(property, environment.getProperty(property));
   }

But the value still is null. In the test class I use following annotations:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyApplication.class)
@SpringBootTest(classes=MyApplication.class)

For loading context from the main class where I manually set the necessary value. Also tried use @TestPropertySource("classpath:application.properties") But nothing help. And I can't hardcode the value. It's should be get only from application.properties

UPDATE It was my mistake. I've tried getValue from static method :/ Maybe someone know how I can disable class test by use this value? The @IfProfileValue still return null and therefore doesn't fit.

UPDATE I've realized that disabling is useless and better just use appropriate config using @SpringBootTest(classes=AppropriateConfigClass.class)

I'll choose gargkshitiz answer as solved, because he was the only one who tried to help.

like image 479
Andr1i Avatar asked Oct 18 '25 06:10

Andr1i


1 Answers

You are halfway there. @TestPropertySource reads from src/test/resources. Add src/test/resources/application.properties with overridden values and you should be done.

like image 193
gargkshitiz Avatar answered Oct 19 '25 20:10

gargkshitiz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!