【问题标题】:Mockito exception : org.mockito.exceptions.misusing.InvalidUseOfMatchersExceptionMockito 异常:org.mockito.exceptions.misusing.InvalidUseOfMatchersException
【发布时间】:2013-08-14 07:57:23
【问题描述】:

我有这个代码:

import static org.mockito.Mockito.*;

final Combobox combobox = mock(Combobox.class);

//.... some business logic which calls method 'appendChild' on 'combobox'

verify(combobox, times(3)).appendChild((Component) anyObject()); // <<== exception here

它一直这样写:

Invalid use of argument matchers!
2 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.  

appendChild 方法如下所示:

public final boolean appendChild(Component child)
{
     return insertBfr(null, child);
}

【问题讨论】:

  • 哪一行抛出异常?请在此处发布您的 SSCCE (sscce.org)。
  • 方法appendChild 是否有不同的版本(具有不同数量的参数)?你能告诉我们这个方法的代码吗?
  • 你为什么使用anyObject?在泛型中使用any 和您的类。看看会发生什么。

标签: java mockito


【解决方案1】:

appendChild 是 final 方法,表示you can't mock or verify it。 Java 编译器将“final”理解为意味着它可以确定它正在调用哪个实际方法实现,这意味着它可以通过快捷方式直接调用该代码,而不是让 Mockito 潜入并替换实现。总的来说,这是人们推荐not to mock types you don't own or control 的充分理由之一。

重构您的测试,或使用PowerMockito 执行深度字节码魔术来模拟这些最终方法。

(为什么会出现这个异常? Matchers actually affect static state in Mockito。因为你在那一行调用 anyObject,Mockito 仍然是 registers a Matcher。在你下次调用 when 时,Mockito 匹配一个不存在的参数或者verify,或者如果你使用MockitoJUnitRunner,就会被the Mockito usage validator捕获。不管怎样,这是一个很好的捕获,因为代码没有按照你的想法做。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多