5

I'm using mockito to mock my services..

How can I inject mocks in parent class?

Sample:

public abstract class Parent(){

    @Mock
    Message message;

}

public class MyTest() extends Parent{

    @InjectMocks
    MyService myService //MyService has an instance of Message

    //When I put @Mock Message here it works
}

When I run my tests the message in Parent stay null

Lucas
  • 1,251
  • 4
  • 16
  • 34

1 Answers1

4

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.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
mdewit
  • 2,016
  • 13
  • 31