gpt4 book ai didi

java - 获取 "InvalidUseOfMatchersException",即使它被正确使用

转载 作者:太空宇宙 更新时间:2023-11-04 10:13:04 28 4
gpt4 key购买 nike

我有以下模拟对象:

@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 use anyObject(), 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com