mockito测试错误,参数匹配器的使用无效。

huangapple go评论83阅读模式
英文:

mockito test error Invalid use of argument matchers

问题

我一直在为调用jdbcTemplate.query并返回一些数据的方法编写单元测试,但似乎不起作用,抛出异常。

这是代码。

@Test
public void NewDealDaoGetClientOwnershipValuesTest() {
    List<OptionView> optionViews = new ArrayList<OptionView>();
    optionViews.add(new OptionView("one", "two"));

    when(jdbcTemplate.query("<some sql query>", newDealDaoImpl.getResultSetExtractor(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))).thenReturn(optionViews);
    assertEquals(newDealDaoImpl.getClientOwnershipValues(), optionViews);
}

错误消息

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
参数匹配器的使用无效
需要 2 个参数匹配器但记录了 3 个
如果匹配器与原始值结合使用则可能会出现此异常
    // 不正确的用法:
    someMethod(anyObject(), "原始字符串");
在使用匹配器时所有参数都必须由匹配器提供
例如
    // 正确的用法:
    someMethod(anyObject(), eq("通过匹配器的字符串"));

只是提供信息,方法newDealDaoImpl.getResultSetExtractor 需要 3 个参数<String, String, String>。

英文:

I have been getting writing unit tests for a method that invokes jdbcTemplate.query and returns some data. It doesn't seems to be working and throwing exception.

Here's the code.

@Test
	public void NewDealDaoGetClientOwnershipValuesTest() {
		List&lt;OptionView&gt; optionViews = new ArrayList&lt;OptionView&gt;();
		optionViews.add(new OptionView(&quot;one&quot;, &quot;two&quot;));

		when(jdbcTemplate.query(&quot;&lt;some sql query&gt;&quot;, newDealDaoImpl.getResultSetExtractor(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))).thenReturn(optionViews);
		assertEquals(newDealDaoImpl.getClientOwnershipValues(), optionViews);
	}

Error message

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 3 recorded.
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), &quot;raw String&quot;);
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq(&quot;String by matcher&quot;));

Just for your information that method newDealDaoImpl.getResultSetExtractor takes 3 arguments<String, String, String>.

答案1

得分: 2

问题在于你正在使用参数匹配器:

Mockito.anyString()

在一个未由Mockito管理的对象上(mock、spy等)。

尝试将空字符串或其他随机值传递给你的:

newDealDaoImpl.getResultSetExtractor(...)
英文:

The problem is that you are using argument matchers:

Mockito.anyString()

on an object that is not managed by Mockito (mock, spy etc.)

Try to pass an empty String or other random value to your:

newDealDaoImpl.getResultSetExtractor(...)

huangapple
  • 本文由 发表于 2020年8月6日 18:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63281666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定