假设我有一个这样的类(class):
//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模拟它呢?
最佳答案
这可能非常危险,但可以做到。
//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);
关于java - 如何从mockito中的另一个包访问 protected 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995596/