Mockito.mockedStatic for method with arguments

五迷三道 提交于 2021-01-18 04:35:28

问题


All the examples provided for mockedStatic method is for method without parameters. Is there a way to mock methods with parameters.

examples provided: 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"))


回答1:


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


来源:https://stackoverflow.com/questions/63172397/mockito-mockedstatic-for-method-with-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!