简体   繁体   中英

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

I need to mock a protected method in the parent class of my class under test but the parent class is in a different package. I thought that the solution would be to use PowerMockito.spy() but I cannot instantiate the type Child because it is abstract. There's gotta be a solution for this issue without refactoring.

Here's the Dependencies.

        <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"/> 

This is legacy code so I cannot refactor, but here's the simplified code.

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;
    }
}

You can use PowerMock to mock methods that are not public

@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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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