Reputation: 1942
I have 3 classes:
public class SomeDAO {
// that method I'd want to catch and change
public void getObj() { ... }
}
public class MainService {
private Service2 service2;
public void doMain() {
service2.doSomethingAnother();
}
}
public class Service2 {
private SomeDAO someDAO
public void doSomethingAnother() {
someDAO.getObj();
}
}
All I need - to call doMain but with custom someDao.getObj() inside service2.doSomethingAnother():
public TestClass {
@InjectMocks
private final MainService mainService = new MainService();
@InjectMocks
private final Service2 service2 = new Service2();
@Mock
private SomeDAO someDao;
@Test
public void testMe() {
// substitution
when(someDao.getObj()).thenReturn(new MyObj());
// then I'm calling the outer method
mainService.doMain();
}
}
When running that test I have NPE in mainService.doMain(): service2 in null..
Inside of testMe object service2 is alive and not null, it has been declared as class variable and initialized.
Whether I misundersood @InjectMock behaviour?
Upvotes: 0
Views: 5750
Reputation: 15982
Service2
is not injected into MainService
, since it is not a mock. Therefore, the server2
attribute of your mainService
object is null
.
You are also trying to mock too deep. The correct way to test MainService
is to mock the dependency of Service2
and not SomeDAO
.
A separate test class for Service2
is better where you mock the dependency of SomeDAO
.
public TestClass {
@InjectMocks
private MainService mainService;
@Mock
private Service2 service2;
@Before
public void setUp() {
initMocks(this);
}
@Test
public void testMe() {
mainService.doMain();
verify(service2).doSomethingAnother();
}
}
Upvotes: 7