我想模仿一个继承的保护方法.我不能直接从java代码调用这个方法,因为它继承自另一个包中的类.我找不到一种方法来指定这个方法来存根(…)
package a; public class A() { protected int m() {} } package b; public class B extends a.A { // this class currently does not override m method from a.A public asd() {} } // test package b; class BTest { @Test public void testClass() { B instance = PowerMockito.spy(new B()); PowerMockito.when(instance, <specify a method m>).thenReturn(123); //PowerMockito.when(instance.m()).thenReturn(123); -- obviously does not work } }
我看着PowerMockito.when覆盖,这似乎只是私人的方法!
如何指定protected方法?
坚果:不能总是使用什么时候存根间谍;使用doReturn
假设静态导入spy和doReturn(都是PowerMockito):
@RunWith(PowerMockRunner.class) @PrepareForTest(B.class) public class BTest { @Test public void testClass() throws Exception { B b = spy(new B()); doReturn(42).when(b, "m"); b.asd(); } }
你也可以@PrepareForTest(A.class),并在(a,“m”)上设置doReturn.这更有意义取决于实际测试.
http://stackoverflow.com/questions/8312212/mocking-protected-method