Issue
I have the following set of classes:
public abstract class ParentClass {
@Autowired
private SomeService service;
protected Item getItem() {
return service.foo();
}
protected abstract doSomething();
}
@Component
public ChildClass extends ParentClass {
private final SomeOtherService someOtherService;
@Override
protected doSomething() {
Item item = getItem(); //invoking parent class method
.... do some stuff
}
}
Trying to test the Child class:
@RunWith(MockitoJUnitRunner.class)
public class ChildClassTest {
@Mock
private SomeOtherService somerOtherService;
@Mock
private SomerService someService; //dependency at parent class
@InjectMocks
private ChildClass childClass;
public void testDoSomethingMethod() {
Item item = new Item();
when(someService.getItem()).thenReturn(item);
childClass.doSomething();
}
}
The matter is that I'm always getting a NullPointerException because the parent dependency (SomeService) is always null.
Also tried:
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return new Item();
}
}).when(someService).getItem();
And using Spy, without any success.
Thanks for your hints.
Solution
One option is using ReflectionTestUtils class to inject the mock. In the code bellow I've executed the unit tests with JUnit 4.
@RunWith(MockitoJUnitRunner.class)
public class ChildClassTest {
@Mock
private SomeService someService;
@Test
public void test_something() {
ChildClass childClass = new ChildClass();
ReflectionTestUtils.setField(childClass, "service", someService);
when(someService.foo()).thenReturn("Test Foo");
assertEquals("Child Test Foo", childClass.doSomething());
}
}
Answered By - VagnerPl
Answer Checked By - Clifford M. (JavaFixing Volunteer)