Android在用Mockito测试的时候可能会出现静态方法的测试
模板如下
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
但是这样mock是一个对象,通常的静态方法是通过类直接调用的如果不用verify
就会爆出相面的错误
org.mockito.exceptions.base.MockitoException:
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()
Examples of correct argument capturing:
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
自己考虑了好久没有任何头绪,刚好老大过来帮我,结果一句话就搞定了
在测试调用的方法前面加上 PowerMockito.verifyStatic();
- 验证静态方法:
PowerMockito.verifyStatic();
Static.firstStaticMethod(param);
- 扩展验证:
PowerMockito.verifyStatic(Mockito.times(2)); // 被调用2次
Static.thirdStaticMethod(Mockito.anyInt()); // 以任何整数值被调用