Search code examples
javamockitosuperclass

How to inject mock into @Autowired field in an abstract parent class with Mockito


I'm writing a Unit test for a class that has an abstract superclass, and one of the functions in the ChildClass is calling a method on an object form the BaseClass.

ChildClass looks something like this.

public class ChildClass extends ParentClass {
    public void functionA(){
        objectFromParentClass.functionB();
    }
}

The parent class

public abstract class ParentClass {
    @Autowired
    protected typeFromParentClass objectFromParentClass;

    public void someFunction() {}
}

Since a parent class is abstract @InjectMocks and ReflectionTestUtils() doesn't work. Is there any way to inject a mocked objectFromParentClass into the ParentClass with Mockito?

Edit: Neither the Child nor the Parent class was written by me, i'm just testing it.


Solution

  • ReflectionTestUtils.setField() does work in this case