简体   繁体   中英

How to decouple System.getenv from static field in java

I've a legacy code as below

@Service
public class CLConf {
    static final String CI_ENV = System.getenv("ENV").toUpperCase(); <-- NPE when doing junits
    // other config variables
}

This works when we run the code normally in application. but I've issues creating test cases that use class CLConf something like below.

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ContextConfiguration(classes = CLConf.class) <<----------- ISSUE while loading bcz env is not set yet
public class CLServiceTest {
    //test cases
}

currently it throws NPE because of .toUpperCase()

Since CI_ENV is directly being set from System.getenv , while writing class for Junits, this class is loaded using @ContextConfiguration . And I'm not sure where to set env variables for Test cases so that it doesn't break while loading CLConf .

How do I configure/do setup for test cases OR how do i decouple System.getenv so that I can supply my own config while testing?

Note: there are many System.getenv in class CLConf, above is just minified class.

You can provide test configurations using the locations or value attribute of the TestPropertySource annotation, directly defining your test properties in a file or selectly override properties like stated in the documentation:

@TestPropertySource is a class-level annotation that is used to configure the locations() of properties files and inlined properties() to be added to the Environment's set of PropertySources for an ApplicationContext for integration tests. Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application declaratively via @PropertySource or programmatically (eg, via an ApplicationContextInitializer or some other means). Thus, test property sources can be used to selectively override properties defined in system and application property sources

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM