PowerMock:来自父类的存根方法

2022-09-01 21:24:26

我正在使用PowerMock,我想知道如何保留子类的所有行为,但存根调用可能会被子类覆盖。super

假设我有这门课:

public class A {
    public String someMethod() {
        return "I don't want to see this value";
    }
}

和一个子类:

public class B extends A {
    @Override
    public String someMethod() {
        return super.someMethod() + ", but I want to see this one";
    }
}

如何将调用存根到 ?super.someMethod()

我试过了

@Test
public void test() {
    B spy = PowerMockito.spy(new B());
    PowerMockito.doReturn("value").when((A)spy).someMethod();

    assertEquals("value, but I want to see this one", spi.someMethod());
}

答案 1

您可以尝试禁止显示父类中的方法,

PowerMockito.suppress(methodsDeclaredIn(A.class));

这是一篇关于Stubbing,抑制和替换为PowerMock的文章,可能会有所帮助。

https://www.jayway.com/2013/03/05/beyond-mocking-with-powermock/


答案 2

不要忘记添加测试类。然后,您可以按照 Steve 的建议执行操作,并在父级中抑制方法:@PrepareForTest({ParentClassToSupress.class})PowerMockito.suppress(methodsDeclaredIn(ParentClassToSupress.class));


推荐