Search code examples
javamockitointegration-testing

Mockito. How to mock a static method with args for integration tests


I use mockito-core 5.4.0 and try to mock a static method with arguments, but it doesn't work.

public record TestObject(
   String test
) {}

public class MyClass {
   public static String staticMethod(TestObject obj) {
     // do some logic
   }
}

======================================
var mock = Mockito.mockStatic(MyClass.class)
mock.when(() -> MyClass.staticMethod(any()).thenReturn("")

And I'd want to return from mocked static method value of TestObject::test. e.g. somewhere in deep of my code:

var testObj = new TestObject("someTest");
var res = MyClass.staticMethod(testObj);
sout(res) // here I'd want to see: someTest 

How can I implement it?


Solution

  • You can use thenAnswer to acomplish it:

        try (MockedStatic<MyClass> mock = Mockito.mockStatic(MyClass.class)) {
            mock.when(() -> MyClass.staticMethod(Mockito.any(TestObject.class))).thenAnswer(
                    (Answer<String>) invocation -> {
                        TestObject arg = invocation.getArgument(0);
                        return arg.test();
                    }
            );
    
            var testObj = new TestObject("someTest");
            var res = MyClass.staticMethod(testObj);
            System.out.println(res);
        }
    

    its documented here: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#answer_stubs