不能使用Mockito模拟方法中声明的局部变量。你可以
ObjectMapper
你班的财产
MyClass
。但如果您不想这样做,另一种选择是在
类名
返回的实例
ObjectMapper
public class MyClass {
public String getString() {
// object need mocking
ObjectMapper mapper = createObjectMapper()
try {
// method need mocking
return mapper.writeValueAsString(List.of("1", "2"));
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
protected ObjectMapper createObjectMapper() {
return new ObjectMapper();
}
}
然后在您的测试用例中,您可以
spy
您的类并存根这个新方法,以返回一个mocked
ObjectMapper
如下所示:
@Test
public void test_get_string() throws Exception {
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mapper.writeValueAsString(Mockito.anyList()))
.thenThrow(JsonProcessingException.class);
MyClass myClass = Mockito.spy(new MyClass ());
doReturn(mapper).when(myClass).createObjectMapper();
Assertions.assertThrows(RuntimeException.class, () -> {
myClass.getString();
});
}