繁体   English   中英

当父级位于不同的程序包中且子类为Abstract时,模拟受保护的父级方法

[英]Mock Protected Parent Method When the Parent is in a Different Package and the Child Class is Abstract

我需要在被测类的父类中模拟一个受保护的方法,但是父类在另一个包中。 我以为解决方案是使用PowerMockito.spy()但是我无法实例化Child类型,因为它是抽象的。 无需重构就可以解决此问题。

这是依赖关系。

        <dependency org="org.powermock" name="powermock-core" rev="1.6.4"/>
        <dependency org="org.powermock" name="powermock-module-junit4" rev="1.6.4"/>
        <dependency org="org.powermock" name="powermock-api-mockito" rev="1.6.4"/> 

这是遗留代码,因此我无法重构,但这是简化的代码。

Parent.java

package parent;

public class Parent {

    // Want to mock this protected parent method from different package
    protected String foo() {

        String someValue = null;

        // Logic setting someValue

        return someValue;
    }
}

Child.java

package child;

import parent.Parent;

public abstract class Child extends Parent {

    String fooString = null;

    public String boo() {

        this.fooString = this.foo();

        String booString = null;

        // Logic setting booString

        return booString;
    }
}

您可以使用PowerMock模拟不公开的方法

@RunWith(PowerMockRunner.class)
public class ChildTest {

   @Test
   public void testBoo() throws Exception {
      Child child = PowerMockito.mock(Child.class);
      PowerMockito.when(child, "foo").thenReturn("someValue");
      PowerMockito.doCallRealMethod().when(child).boo()
      String boo = child.boo();

      //assert here whatever you want to assert
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM