mockito 如何用args模拟静态方法进行集成测试

uinbv5nw  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(145)

我使用mockito-core 5.4.0并尝试用参数模拟静态方法,但它不起作用。

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("")

字符串
我想从模拟的静态方法TestObject::test返回值。在我的代码深处:

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


我该如何实施?

k2arahey

k2arahey1#

你可以使用thenAnswer来完成它:

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);
    }

字符串
其记录在这里:https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#answer_stubs

相关问题