I'm using Mockito, along with mockito-inline for mocking static methods. I'm trying to apply doNothing
or similar behavior, to a static void method. The following workaround work, but I think that there should have a more convenient way to achieve this with less code.
try (MockedStatic<UtilCalss> mock = Mockito.mockStatic(UtilCalss.class)) {
mock.when(() -> UtilCalss.staticMethod(any()))
.thenAnswer((Answer<Void>) invocation -> null);
}
If it's a non-static method, we could simply do:
doNothing().when(mock).nonStaticMethod(any());
But I want to do the same for a static method.
You don't need to stub that call.
doNothing
is a default behaviour of a void
method called on a mock.
Example:
Class under test:
public class UtilClass {
public static void staticMethod(String data) {
System.out.println("staticMethod called: " + data);
}
}
Test code:
public class UtilClassTest {
@Test
void testMockStaticForVoidStaticMethods() {
try (MockedStatic<UtilClass> mockStatic = Mockito.mockStatic(UtilClass.class)) {
UtilClass.staticMethod("inMockStaticScope");
}
UtilClass.staticMethod("outOfMockStaticScope");
}
}
Output:
staticMethod called: outOfMockStaticScope