模棱两可的 Mockito - 预期 0 个匹配器,记录 1 个(InvalidUseOfMatchersException)

Ambiguous Mockito - 0 Matchers Expected, 1 Recorded (InvalidUseOfMatchersException)

我遇到了一个很奇怪的问题。

 URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 eq(this.config.apiEndpoint() + URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

甚至包含

 URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 contains(this.config.apiEndpoint() + URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

给我

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

即使我不使用 RAW 表达式。
奇怪的是,如果我将 contains 方法更改为:

URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 contains(URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

省略端点,有效。

Config 和 RestHelper 都被 mock 了:

this.restHelperMock = mock(RESTHelper.class);
this.config = mock(MyConfiguration.class);

when(this.config.apiEndpoint()).thenReturn("http://host:port/api");

带ApiEndpoint的URL等于我想模拟的, 即使不是,我也应该得到一个 NullpointerException,因为错误的模拟。 但是这里我没有任何想法。

感谢您的回答。

问题似乎是您在 eq ( ... ) 调用期间调用了模拟方法 this.config.apiEndpoint()。尝试简单地将完整的 URL 放在那里( host:port/api/my/specific/url )而不是在那里调用另一个模拟,这可能会使 Mockito 感到困惑,因为它依赖于内部状态进行模拟。

老实说,我对 Mockito 的了解还不够深入,我无法解释为什么会发生这种情况,但我可能有一天会尝试对其进行调试 ;-)

编辑:奇怪的是,我似乎无法用更简单的测试用例重现它。好像还不止这些。