Java 如何从mockito中的另一个包访问受保护的方法?
假设我有一门课是这样的:Java 如何从mockito中的另一个包访问受保护的方法?,java,testing,mocking,mockito,Java,Testing,Mocking,Mockito,假设我有一门课是这样的: //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
//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!
.....
}
}
并进行如下测试:
//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中的类位于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);
您必须使用PowerMock来实现这一点。PowerMock不是我想要的,问题是关于mockito本身