我有以下模拟对象:
@Mock
ObjectMapper objectMapper = new ObjectMapper();
然后我写了一些 mock 逻辑,声称我做错了:
Mockito.when(objectMapper.writeValueAsString(Mockito.anyObject())).thenThrow(JsonProcessingException.class);
我哪里出错了?
最佳答案
Matcher methods like
anyObject()
,eq()
do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null). This implementation is due to static type safety imposed by the java compiler. The consequence is that you cannot useanyObject()
,eq()
methods outside of verified/stubbed method.
我的建议是使用any()
例如
@Test
public void TestObjectMapper() {
//Arrange
ObjectMapper objectMapper = mock(ObjectMapper.class);
when(objectMapper.writeValueAsString(any()))
.thenThrow(new JsonProcessingException());
//...
}
关于java - 获取 "InvalidUseOfMatchersException",即使它被正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086808/