PowerMockito测试方法内对象问题
当测试如下类时
Class A {
public boolean myMethod(someargs) {
MyQueryClass query = new MyQueryClass();
Long id = query.getNextId();
// some more code
}
}
Class MyQueryClass {
....
public Long getNextId() {
//lot of DB code, execute some DB query
return id;
}
}
测试代码中想mock MyQueryClass
.因此写代码如下:
MyQueryClass query = PowerMockito.mock(MyQueryClass.class);
PowerMockito.whenNew(MyQueryClass.class).withNoArguments().thenReturn(query);
when(query.getNextId()).thenReturn(1000000L);
boolean b = A.getInstance().myMethod(args);
//asserts
同时在测试类头部使用
@RunWith(PowerMockRunner.class)
and @PrepareForTest({MyQueryClass.class})
in the beginning of my test class.
但是当调试代码时, i仍然调用真实的getNextId()
方法而非mock的。
问题解决:
你需要把调用构造函数的类而非需要创建的类加入@PrepareForTest,因此:
✗ @PrepareForTest(MyQueryClass.class)
✓ @PrepareForTest(A.class)
更普遍性的是:
✗ @PrepareForTest(NewInstanceClass.class)
✓ @PrepareForTest(ClassThatCreatesTheNewInstance.class)