Spring: unit test for class that has both field and injection constructor
I have below class settings.
class Base {
@Autowired
private BaseService service; //No getters & setters
....
}
@Component
class Child extends Base {
private final SomeOtherService otherService;
@Autowired
Child(SomeOtherService otherService) {
this.otherService = otherService;
}
}
I am writing a unit test for a class Child
. If I use @InjectMocks
then otherService
will be null. If I use the class constructor Child
in the test setup, then the fields in the class Base
look like null
.
I know all the arguments are for field injection, but I am more interested in knowing if there is a way to solve this problem without changing the way the classes Base
and Child
inject their properties?
Thank!!
source to share
Just do the following:
public class Test {
// Create a mock early on, so we can use it for the constructor:
OtherService otherService = Mockito.mock(OtherService.class);
// A mock for base service, mockito can create this:
@Mock BaseService baseService;
// Create the Child class ourselves with the mock, and
// the combination of @InjectMocks and @Spy tells mockito to
// inject the result, but not create it itself.
@InjectMocks @Spy Child child = new Child(otherService);
@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
}
Mokito must do the right thing.
source to share