模拟受保护方法

2022-09-03 05:40:44

我想模拟一个继承的受保护方法。我不能直接从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

如何指定受保护的方法?


答案 1

坚果壳:不能总是用来存根间谍;用。whendoReturn

假设 静态导入 和 (两者):spydoReturnPowerMockito

@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)doReturnwhen(a, "m")


答案 2

推荐