假设我有一个这样的课程:
//this is src/a/b
package a.b;
class C
{
protected Api getApi();
}
并像这样测试:
//and this is test/a/d
package a.d;
class TestE {
@Test
public void test()
{
C mockedC = spy(new C());
doReturn(*somemockedapi*).when(mockedC).getApi(); // this one doesn't work!
.....
}
}
如果测试中的类在tests / a / b中,它将起作用,但这不是解决方案,因为我们需要从src / a / d访问一些东西。显然这个函数可以通过继承访问,所以有没有办法让mockito在这种情况下嘲笑它?
答案 0 :(得分:2)
这可能非常危险,但可以做到。
//reflectively get the method in question
Method myMethod = mockedC.getClass().getDeclaredMethod("getApi");
//manually tell java that the method is accessible
myMethod.setAccessible(true);
//call the method
myMethod.invoke(myClass, null);
//PLEASE SET THE FIELD BACK TO BE UNACCESSIBLE
myMethod.setAccessible(false);