Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从mockito中的另一个包访问受保护的方法?_Java_Testing_Mocking_Mockito - Fatal编程技术网

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本身