首先,简单说说PowerMockito进行单元测试的三部曲:
- 打桩,即为非测试目标方法设置返回值,这些返回值在测试目标方法中被使用。
- 执行测试,调用测试目标方法。
- 验证测试结果,如测试方法是否被执行,测试结果是否正确等。
其次,在使用PowerMockito框架进行单元测试的过程中,经常遇到如下异常:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at com.mycompany.myproject.mypackage.MyTestClass.myTestMethod(MyTestClass.java:65)
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.
乍一看似乎找不到北,先看看下面的代码再说。
被测试方法如下:
public boolean toggleOffOn(int delaySeconds) {
boolean off = powerOff();