Mockito. 如何为集成测试模拟带有参数的静态方法

huangapple go评论76阅读模式
英文:

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&lt;MyClass&gt; mock = Mockito.mockStatic(MyClass.class)) {
        mock.when(() -&gt; MyClass.staticMethod(Mockito.any(TestObject.class))).thenAnswer(
                (Answer&lt;String&gt;) invocation -&gt; {
                    TestObject arg = invocation.getArgument(0);
                    return arg.test();
                }
        );

        var testObj = new TestObject(&quot;someTest&quot;);
        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

huangapple
  • 本文由 发表于 2023年7月13日 22:11:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76680342.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定