当我测试这个静态方法时
public class SomeClass {
public static long someMethod(Map map, String string, Long l, Log log) {
...
}
}
with
import org.apache.commons.logging.Log;
@RunWith(PowerMockRunner.class)
//@PrepareForTest(SomeClass.class)
public class Tests {
@Test
public void test() {
...
PowerMockito.mockStatic(SomeClass.class);
Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), isA(Log.class))).thenReturn(1L);
...
}
}
I got InvalidUseOfMatchersException
。我的问题是:
- 当所有参数都使用匹配器时,为什么我会遇到此异常?怎么解决呢?我调试了一下,发现
isA(Log.class)
返回空值。
- 当我添加
@PrepareForTest
注解到测试类并运行测试,junit 没有任何响应。为什么?
EDIT
我尝试不使用参数匹配器,然后得到
org.mockito.exceptions.misusing.MissingMethodInitationException:
when() 需要一个参数,该参数必须是“模拟上的方法调用”。
例如:
when(mock.getArticles()).thenReturn(文章);
此外,出现此错误的原因可能是:
您可以存根以下任一方法:final/private/equals()/hashCode() 方法。
那些方法cannot被存根/验证。
在 when() 内部,您不会在模拟上调用方法,而是在其他对象上调用方法。
at ...
所以看来是由于someMethod
本身。有同步的方法中的块。我想知道 Powermockito 是否可以模拟这种方法。
尝试将 isA() 替换为另一个 any() 调用,如下所示
Mockito.when(SomeClass.someMethod(anyMap(), anyString(), anyLong(), any(Log.class))).thenReturn(1L);
[EDIT]
收到异常时检查堆栈跟踪。你看到任何NoClassDefFoundError
报道了?我注意到当我没有包括javassist.jar
在我的项目中,我遇到了与你类似的错误。
我使用 PowerMockito,这些是我添加到一个全新项目中的 jar,用于运行 @Tom 发布的代码
- powermock-mockito-1.4.10-full.jar
- 模拟-all-1.8.5.jar
- javassist-3.15.0-GA.jar
- junit-4.8.2.jar
- common-logging-1.1.1.jar
检查您是否使用兼容的 JAR 版本,并检查项目类路径中是否存在任何其他冲突的 JAR 始终是一个好主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)