PowerMockito单元测试中的Invalid use of argument matchers问题详解

PowerMockito单元测试中的Invalid use of argument matchers问题详解  

首先,简单说说PowerMockito进行单元测试的三部曲:

  1. 打桩,即为非测试目标方法设置返回值,这些返回值在测试目标方法中被使用。
  2. 执行测试,调用测试目标方法。
  3. 验证测试结果,如测试方法是否被执行,测试结果是否正确等。

其次,在使用PowerMockito框架进行单元测试的过程中,经常遇到如下异常:

 
  1. Invalid use of argument matchers!

  2. 0 matchers expected, 1 recorded:

  3. -> at com.mycompany.myproject.mypackage.MyTestClass.myTestMethod(MyTestClass.java:65)

  4. This exception may occur if matchers are combined with raw values:

  5. //incorrect:

  6. someMethod(anyObject(), "raw String");

  7. When using matchers, all arguments have to be provided by matchers.

  8. For example:

  9. //correct:

  10. someMethod(anyObject(), eq("String by matcher"));

  11. For more info see javadoc for Matchers class.

乍一看似乎找不到北,先看看下面的代码再说。

被测试方法如下:

 
  1. public boolean toggleOffOn(int delaySeconds) {

  2. boolean off = powerOff();

  3. sleep(delaySeconds);

  4. boolean on = powerOn();

  5. return off && on;

  6. }

测试用例中的测试方法片段如下:

 
  1. PowerMockito.when(ps.powerOn()).thenReturn(true);

  2. PowerMockito.when(ps.powerOff()).thenReturn(true);

  3. PowerMockito.when(ps.toggleOffOn(Mockito.anyInt())).thenReturn(true);//throws exception here

异常分析:

从异常的位置来看,该异常发生在打桩阶段,还未执行到真正的测试。

从异常的信息来看,显然违反了一个Mockito框架中的Matchers匹配参数的规则。根据Matchers文档如下,在打桩阶段有一个原则,一个mock对象的方法,如果其若干个参数中,有一个是通过Matchers提供的,则该方法的所有参数都必须通过Matchers提供。而不能是有的参数通过Matchers提供,有的参数直接给出真实的具体值。

 
  1. If you are using argument matchers, all arguments have to be provided by matchers.

  2. E.g: (example shows verification but the same applies to stubbing):

  3.  
  4. verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));

  5. //above is correct - eq() is also an argument matcher

  6. verify(mock).someMethod(anyInt(), anyString(), "third argument");

  7. //above is incorrect - exception will be thrown because third argument is given without argument matcher.

  8.  
  9. Matcher methods like anyObject(), eq() do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null).

上述文档中给出的示例,可以使用eq()方法将真实的具体值转换为Matchers提供的值。

解决方法:

给出具体值
PowerMockito.when(ps.toggleOffOn(3)).thenReturn(true);
或直接去掉(仅适用于该测试用例)
PowerMockito.when(ps.toggleOffOn(Mockito.anyInt())).thenReturn(true);

注意:在Mockito 1.x中,org.mockito.Matchers已经过时,org.mockito.Mockito继承自Matchers,用以取代Matchers。

 

参考链接:

http://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值