16

我想模拟一个继承的受保护方法。我不能直接从java代码调用这个方法,因为它是从另一个包中的类继承的。我找不到一种方法来指定这个方法来存根when(...)

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覆盖,这似乎都只用于私有方法!

如何指定受保护的方法?

4

1 回答 1

26

简而言之:不能总是when用来存根间谍;使用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)设置doReturnon when(a, "m")。哪个更有意义取决于实际测试。

于 2011-11-29T14:35:49.153 回答