英文:
Mockito. How to mock a static method with args for integration tests
问题
我使用mockito-core 5.4.0并尝试模拟带有参数的静态方法,但它不起作用。
public record TestObject(
String test
) {}
public class MyClass {
public static String staticMethod(TestObject obj) {
// 执行一些逻辑
}
}
======================================
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) // 这里我想看到: someTest
如何实现它?
英文:
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?
答案1
得分: 0
你可以使用 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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论