问题
I am trying to use some of the new features of Mockito, specifically mocking of static methods.
I am able to get it to work when the method I am mocking has no parameters, but for some reason it will not work if the method has any parameters.
As the example below is written, the test assertEquals( "bar", Foo.foo() )
works but the test assertEquals(2, map.size() )
fails as no behavior has been defined for the mocked class.
fooMock.when(Foo::genMap).thenCallRealMethod()
gives the follwing compile time errors:
- The type Foo does not define genMap() that is applicable here
- The method when(MockedStatic.Verification) in the type MockedStatic is not applicable for the arguments (Foo:: genMap)
fooMock.when( (String s)->Foo.genMap(s) ).thenCallRealMethod()
gives these compile time errors:
- The method when(MockedStatic.Verification) in the type MockedStatic is not applicable for the arguments ((String s) -> {})
- Lambda expression's signature does not match the signature of the functional interface method apply()
Unit Test:
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Test
public void fooTest(){
try( MockedStatic<Foo> fooMock = Mockito.mockStatic(Foo.class) ){
fooMock.when(Foo::foo).thenReturn("bar");
assertEquals( "bar", Foo.foo() );
//fooMock.when(Foo::genMap).thenCallRealMethod();
//fooMock.when( (String s)->Foo.genMap(s) ).thenCallRealMethod();
Map<String, String> map = Foo.genMap("1=one 2=two");
assertEquals(2, map.size() );
}
}
}
Class to be mocked
public class Foo {
public static String foo() {
return "foo";
}
public static Map<String, String> genMap(String str){
Map<String, String> map = new HashMap<String, String>();
for(String subStr : str.split(" ")) {
String[] parts = subStr.split("=");
map.put(parts[0], parts[1]);
}
return map;
}
}
It looks like it is a simply a syntax issue, I am not super familiar with method references but I cannot figure out what the proper syntax would be.
回答1:
This is the correct syntax
fooMock.when( () -> Foo.genMap(any()) ).thenCallRealMethod();
anyString()
can be used, but there shouldn't be any difference because it's not ambiguous.
来源:https://stackoverflow.com/questions/64809471/unable-to-mock-static-methods-with-parameters-using-mockito