I have MyClass
with
- public
doSomething
- method to be tested - protected static
getYourStaticBool
- method to be mocked, containsSystem.getenv
method which cannot be mocked - static boolean
MY_STATIC_BOOL
- it has to be static and the value is provided bygetYourStaticBool
MyClass:
public class MyClass {
private static boolean MY_STATIC_BOOL = getYouStaticBool();
public void doSomething() {
if (MY_STATIC_BOOL) {
//....
}
}
protected static boolean getYourStaticBool() {
return Optional.ofNullable(System.getenv("foo"))
.map(Boolean::parseBoolean)
.orElse(false);
}
}
Now I want to doSomething
so I have to mock getYourStaticBool
to set MY_STATIC_BOOL
on true.
@ExtendWith(MockitoExtension.class)
public class MyClassTest {
private MyClass myClass = new MyClass();
@BeforeAll
void static init() {
try (MockedStatic<MyClass> myClass = Mockito.mockStatic(MyClass.class)) {
myClass.when(() -> MyClass.getYourStaticBool())
.thenReturn(true);
}
}
@Test
void shouldDoSth() {
myClass.doSomething();
}
}
Unfortunately calling myClass.doSomething()
reveals that MY_STATIC_BOOL
is false. So the real getYourStaticBool
is called, not the mocked one.
Maybe should I use spy and mock static getYourStaticBool
? I can't use PowerMockito.