Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito.mockedStatic for method with arguments

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

like image 394
sbha Avatar asked Jul 30 '20 11:07

sbha


1 Answers

Edit - Mockito 3.7.7

Mockito 3.7.7 unified order of verify parameters (Issue #2173)

Updated code:

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

Original answer

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")
    );
}
like image 199
Lesiak Avatar answered Oct 18 '22 06:10

Lesiak