我已经实现了一个B类,它是现有抽象类A
的子类抽象类(基本上):
public abstract class A {
public A(Properties p, ArrayList<XXX> list) {
...
}
// There is no 0-arg constructor
protected int doSomeWork() {
return ...;
}
protected SomeObject[] findObjectsByQuery(String query) {
return ...;
}
}
我自己的班级
public class B extends A {
// this is the method I want to test
protected int doSomeWork() {
...
// calling method of super class
// this call I want to mock/stub/whatever
// to either return null or a mock object
SomeObject[] myobjects = findObjectsByQuery(queryString);
...
}
}
如您所见,我想测试的方法也受到保护。这就是为什么我创建了一个继承自B的内部类Btest,仅用于测试目的:
private class Btest extends B {
public Btest(Properties prop) {
super(prop, null);
}
public int doSomeWork() {
return super.doSomeWork();
}
}
我的测试方法是使用Mockito和PowerMock。这就是我到目前为止所做的:
@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class Tester {
@Test
public void testWrongQueryString() throws Exception {
Properties prop = new Properties();
Btest testObject = new Btest(prop);
// what am I supposed to do here?
// essentially I want to do something in the lines of
// PowerMockito.when(/* there is a call to A.findObjectsByQuery or B.findObjectsByQuery with parameter "QueryString" */)
// .thenReturn(null);
int result = testObject.doSomeWork();
Assert.assertEquals(2, result);
}
}
这就是我试过的:
// gives an InvocationTargetException
Btest spy = PowerMockito.spy(testObject);
PowerMockito.when(spy, "findObjectsByQuery", "QueryString").thenReturn(null);
// will not return NULL
A mock = Mockito.mock(A.class);
PowerMockito.when(mock, "findObjectsByQuery", "QueryString").thenReturn(null);
我该怎么办呢?
答案 0 :(得分:1)
我认为它应该是这样的:
Btest spy = PowerMockito.spy(testObject);
PowerMockito.doReturn(null).when(spy, "findObjectsByQuery");
答案 1 :(得分:0)
我的问题是我用testObject.doSomeWork()
而不是spy.doSomeWork()
它的工作原理如下:
Btest spy = PowerMockito.spy(testObject);
PowerMockito.doReturn(null).when(spy, "findObjectsByQuery", Mockito.someString());
与
int result = spy.doSomeWork();