Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito doNothing with Mockito.mockStatic

Tags:

mockito

junit5

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.

like image 898
Gayan Weerakutti Avatar asked Nov 16 '25 02:11

Gayan Weerakutti


2 Answers

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
like image 96
Lesiak Avatar answered Nov 18 '25 19:11

Lesiak


mockito-inline include mockito-core :

        <!-- Mockito-inline include Mockito-code in same version - Useful for Mock static method -->
        <!-- See https://asolntsev.github.io/en/2020/07/11/mockito-static-methods/ -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-inline</artifactId>
            <version>3.6.28</version>
        </dependency>

And if static method you are testing return nothing => don't use mock.when => just execute the method you want to test and verify :

try (MockedStatic<UtilClass> mock = Mockito.mockStatic(UtilClass.class)) {

     mock.when(() -> UtilClass.staticMethod(any()))
            .thenAnswer((Answer<Void>) invocation -> null);

     App.main(null); // example : I'm testing main method from App class

     mock.verify(UtilClass::staticMethod); // I verify static method from UtilClass was called.

}

resources :

  • Mocking static methods with Mockito
  • https://github.com/mockito/mockito/issues/2027 - cf rimuln comment on 16 Oct 2020
like image 40
Vifier Lockla Avatar answered Nov 18 '25 21:11

Vifier Lockla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!