BigDataLearner
BigDataLearner

Reputation: 1468

Test a method by changing final static variables

I have a protected Method which looks as follows.It uses final static variables from a Constants.java file.

class A {
    protected Configuration connectConfig() {
        ConfigDescriptor desc = new ConfigDescriptor.Builder()
            .project(Constants.REMOTE_CONFIG_PROJECT_NAME)
            .name(Constants.REMOTE_CONFIG_PROJECT_CONFIG_NAME)
            .version(Constants.REMOTE_CONFIG_PROJECT_VERSION)
            .build();

        return ConfigProvider.of(desc, getClass().getClassLoader());
    }

    public boolean process() {
        Configuration config = connectConfig();
        if(config == null) {
            return false;
        }
    }
}

Now I want to unit test this method process for the remote config to fail.

If I just test process() method it will pass since the Constants.java has proper values to connect. For testing I want to change these values so that remote config returns null;

Note : We don't want to use Mockito to mock the values.

Upvotes: 0

Views: 375

Answers (3)

Raedwald
Raedwald

Reputation: 48644

Using a mocking framework is almost always the wrong answer to this kind of question. Use dependency injection instead.

Upvotes: 0

juherr
juherr

Reputation: 5740

You can try to change constant values with byteman. It should do the job.

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53819

Using a mocking framework such as Mockito, you can define a spy of A in which you can specify the result of connectConfig():

A spy = spy(new A());
doReturn(null).when(spy).connectConfig();

Assert.assertFalse(spy.process());

Upvotes: 1

Related Questions