Two ways to solve this:
1) You need to use MockitoAnnotations.initMocks(this)
in the @Before
method in your parent class.
The following works for me:
public abstract class Parent {
@Mock
Message message;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
}
public class MyTest extends Parent {
@InjectMocks
MyService myService = new MyService(); //MyService has an instance of Message
...
}
2) If want to use the @RunWith(MockitoJUnitRunner.class)
above the class definition, then this must be done in the Parent class:
@RunWith(MockitoJUnitRunner.class)
public class Parent {
...
Note that declaring the @Mock
in both the Parent
and MyTest
class will cause the injected object to be null. So you will have to pick where you want to declare this.