Mockito.mockedStatic 用于带参数的方法 [英] Mockito.mockedStatic for method with arguments
本文介绍了Mockito.mockedStatic 用于带参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为 mockedStatic 方法提供的所有示例都是针对没有参数的方法.有没有办法用参数模拟方法.
All the examples provided for mockedStatic method is for method without parameters. Is there a way to mock methods with parameters.
提供的示例:https://javadoc.io/static/org.mockito/mockito-core/3.4.6/org/mockito/Mockito.html#static_mocks
mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);
}
我想要的:我在下面尝试过,但它不起作用.
What I want: I tried below and it does not work.
mocked.when(Foo.methodWithParams(SomeValue"))
推荐答案
编辑 - Mockito 3.7.7
Mockito 3.7.7 统一校验参数顺序(Issue#2173)
Mockito 3.7.7 unified order of verify parameters (Issue #2173)
更新代码:
try (MockedStatic<Foo> dummyStatic = Mockito.mockStatic(Foo.class)) {
dummyStatic.when(() -> Foo.method("param1"))
.thenReturn("someValue");
// when
System.out.println(Foo.method("param1"));
//then
dummyStatic.verify(
() -> Foo.method("param1"),
times(1),
);
}
原答案
有可能,您需要使用 lambda 而不是方法引用:
It is possible, you need to use a lambda instead of a method reference:
try (MockedStatic<Foo> dummyStatic = Mockito.mockStatic(Foo.class)) {
dummyStatic.when(() -> Foo.method("param1"))
.thenReturn("someValue");
// when
System.out.println(Foo.method("param1"));
//then
dummyStatic.verify(
times(1),
() -> Foo.method("param1")
);
}
这篇关于Mockito.mockedStatic 用于带参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文