Search code examples
javaunit-testingjunitmockitopowermockito

How to mock a final static variable that is being set by a static method?


I have looked at other questions which are similar to this, but they don't have this exact use case.

If I have code like the following:

private static final String SOME_CONSANT = SomeStaticClass.getString();

How would I go about mocking this so that it doesn't always return a null pointer exception? I have tried the following but it doesn't seem to work.

PowerMockito.mockStatic(SomeStaticClass.class);
when(SomeStaticClass.getString(Mockito.anyString())).thenReturn("test");

I'm at a loss. Appreciate any help on this.


Solution

  • I presume that the main problem of yours is that you are trying to mock different method.

    With this code when(SomeStaticClass.getString(Mockito.anyString())).thenReturn("test"); you mock method SomeStaticClass.getString(String parameter), however, in your original code you have SomeStaticClass.getString().