VinniK
VinniK

Reputation: 35

How to Mock System Class for Testing?

I have a code to test which depends on the value of environment variable set. How do I mock the setting of system environment variables?? I don't want to do System.setProperty() in my test class which may add the variable to environment.

I just want to mock the setting and test. How do I mock it??

Thanks.

Upvotes: 0

Views: 326

Answers (1)

Dave Syer
Dave Syer

Reputation: 58124

If your code really depends on a System property, I would recommend refactoring it to depend on the Spring Environment instead. Then you can use (with Spring Boot anyway) @IntegrationTest on your Spring test, e.g. (from the docs):

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@IntegrationTest({"foo=bar"})
public class SomeIntegrationTests {

// ...

}

Upvotes: 3

Related Questions