java – Ambiguous Mockito – 0匹配预期,1记录(InvalidUseOfMatchersException)

前端之家收集整理的这篇文章主要介绍了java – Ambiguous Mockito – 0匹配预期,1记录(InvalidUseOfMatchersException)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我面临一个非常奇怪的问题.
  1. URL = "/my/specific/url/";
  2. when(this.restHelperMock.post(
  3. eq(myEnum),eq(this.config.apiEndpoint() + URL),any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

甚至包含

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

给我

  1. org.mockito.exceptions.misusing.InvalidUSEOfMatchersException:
  2. Invalid use of argument matchers!
  3. 0 matchers expected,1 recorded:
  4.  
  5. This exception may occur if matchers are combined with raw values:
  6. //incorrect:
  7. someMethod(anyObject(),"raw String");
  8. When using matchers,all arguments have to be provided by matchers.
  9. For example:
  10. //correct:
  11. someMethod(anyObject(),eq("String by matcher"));
  12.  
  13. For more info see javadoc for Matchers class.

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

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

省略端点,它的工作原理.

Config和RestHelper都被嘲笑:

  1. this.restHelperMock = mock(RESTHelper.class);
  2. this.config = mock(MyBMWConfiguration.class);
  3.  
  4. 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,我可以解释为什么会发生这种情况,但有一天我可能会尝试调试它;-)

编辑:奇怪的是,我似乎无法用更简单的测试用例重现它.这里似乎有更多,而不是满足眼睛.

猜你在找的Java相关文章