Search code examples
javamockitojunit4stubpowermockito

How to Mock or Stub a protected method from abstract parent while testing a public method in child with both in different packages


I have legacy code that I can't change but I need to cover with a JUnit test. I've been trying out various Mockito and PowerMockito usages to no avail.

Abstract Parent

package com.parent;

public abstract class Parent {

    public Parent() {
    }

    protected void badMethod() {
        //code
    }

    // public methods

}

Public Child

package com.child;

public class Child extends Parent {

    public void methodToTest() {
        //code

        badMethod();

        //code
    }
}

The code that I need to test comes after the call to badMethod(). Is there a way to stub, mock, or bypass the badMethod() call? There isn't an @Override for badMethod() in the child class.

The badMethod() call attempts to establish a database connection, as well as making calls to other services. I don't need any of this for the code that I am actually testing.


Solution

  • You can extend the class Child in your test and "disable" the badMethod in the new class.

    public class YourTest {
    
        @Test
        public void testSomething() {
            Child child = new ChildWithDisabledBadMethod();
    
            child.methodToTest();
    
            //put your assertions here
        }
    
        private static class ChildWithDisabledBadMethod extends Child {
            protected void badMethod() {
            }
        }
    }