0

I am using Java 8, Junit5 and Mockito. Is there a way to mock System.env() ?

I have the following code coming from an external dependency and can't modify it.

Seen few examples here but they reference Junit4.

Or asking to use PowerMock which I do not want to use.

Is there a way to mock this or some way around this? Please advice. Thanks.

A method in my class using the legacy class and method

public class MyClass {

    void myMethod() {

        // I need to use this legacyMethod
        Map<String, String> map = ExternalClass.externalMethod();

        // some logic
    }
}

External class which I can't change.

public class ExternalClass {

    public static Map<String, String> externalMethod() {

        // other logic

        // I want to mock this so that the variable name can get a value out of this.
        String name = System.getenv("SOME_ENV_VALUE");

        if(name == null) {
            // test fails cos I end up inside here currently.
            throw new RuntimeException();
        }

        // other logic

        return new HashMap<>();
    }
}
  • @GhostCat Thanks. Seen this before. The mockito example involves changing the externalMethod which I can't do. Having a look again at other examples. And ya don't wanna use Powermock. – JordanHome Sep 11 '20 at 10:16
  • @GhostCat Sorry don't get the example you suggested with EnvProvider. Why would mocking that affect externalMethod? – JordanHome Sep 11 '20 at 10:18
  • 1
    Well, if you have studied that question in detail, you should say that when writing your answer. When you come in "I want to do X", but you dont tell us what you researched before ... then well, such things are going to happen. – GhostCat Sep 11 '20 at 10:18
  • Sorry, you are right. I misread that part. Then your own interface is of no help. – GhostCat Sep 11 '20 at 10:19

0 Answers0