Mockito.mockedStatic 对于带参数的方法
Mockito.mockedStatic for method with arguments
为 mockedStatic 方法提供的所有示例都是针对没有参数的方法。有没有办法模拟带参数的方法。
提供的示例:
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);
}
我想要的:
我在下面尝试过,但它不起作用。
mocked.when(Foo.methodWithParams("SomeValue"))
编辑 - Mockito 3.7.7
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 而不是方法引用:
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")
);
}
为 mockedStatic 方法提供的所有示例都是针对没有参数的方法。有没有办法模拟带参数的方法。
提供的示例: 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);
}
我想要的: 我在下面尝试过,但它不起作用。
mocked.when(Foo.methodWithParams("SomeValue"))
编辑 - Mockito 3.7.7
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 而不是方法引用:
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")
);
}