4

I have such case, I need to set system properties, before I inject testable class, because this class should be init with this system property for test.

To do this I run setting of system vars in @BeforeAll method which is static :

    @Autowired
    private MyService myService;  

    @BeforeAll
    public static void init(){
        System.setProperty("AZURE_CLIENT_ID", "someId");
        System.setProperty("AZURE_TENANT_ID", "someId");
        System.setProperty("AZURE_CLIENT_SECRET", "someSecret" );
    }

And it works perfectly fine.

But now I want to read this property from application.yaml, like :

    @Value("clientId")
    private String clientId;

    @BeforeAll
    public static void init(){
        System.setProperty("AZURE_CLIENT_ID", clientId);
        System.setProperty("AZURE_TENANT_ID", tenantId);
        System.setProperty("AZURE_CLIENT_SECRET", someSecret);
    }

Problem is that I cannot reference non-static from static method and I definitely need to run @BeforeAll first to set System properties.

Any solution for this?

lugiorgi
  • 473
  • 1
  • 4
  • 12
Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39
  • 2
    Does this answer your question? [How to assign a value from application.properties to a static variable?](https://stackoverflow.com/questions/45192373/how-to-assign-a-value-from-application-properties-to-a-static-variable) Check also the second answer. – lugiorgi Feb 04 '20 at 08:21
  • @Iugiorgi second with PropertyExtractor worked for me – Bohdan Myslyvchuk Feb 04 '20 at 09:00
  • 1
    If you want to know why the @BeforeAll method is static read https://stackoverflow.com/questions/1052577/why-must-junits-fixturesetup-be-static the first answer. I found it interesting ;) – lugiorgi Feb 04 '20 at 09:20

1 Answers1

2

Solution proposed in How to assign a value from application.properties to a static variable? in second answer worked for me. Just added

public class PropertiesExtractor {
private static Properties properties;
static {
    properties = new Properties();
    URL url = PropertiesExtractor.class.getClassLoader().getResource("application.properties");
    try{
        properties.load(new FileInputStream(url.getPath()));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String getProperty(String key){
    return properties.getProperty(key);
}

}

And then in my code in static @BeforeAll got all need properties with

PropertiesExtractor.getProperty("clientId")
Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39