Here is my example of object
@Service
public class UserSshKeyService {
private final RecordEventService eventService;
private final UserSshKeyRepository repository;
public UserSshKeyService( RecordEventService eventService,
UserSshKeyRepository repository){}
}
@Service
public class RecordEventService {
private final UserSshKeyEventLogRepository repository;
public UserSshKeyService( UserSshKeyEventLogRepository repository ){
}
}
and
@InjectMocks
private UserSshKeyService userSshKeyService;
@InjectMocks
private RecordEventService eventService;
@Mock
UserSshKeyRepository userSshKeyRepository;
@Mock
UserSshKeyEventLogRepository userSshKeyEventLogRepository;
@InjectMocks
private UserSshKeyService userSshKeyService;
@Spy
@InjectMocks
private RecordEventService eventService;
@Mock
UserSshKeyRepository userSshKeyRepository;
@Mock
UserSshKeyEventLogRepository userSshKeyEventLogRepository;
I tried like this.
but when i execute test code , then event service in UserSshKeyService throw null pointer exception.
how can i inject mock object when multiple level of objects ??
@Mock(answer = RETURNS_DEEP_STUBS)
withwhen(myService.itsInnerService().doSomething).thenReturn('myAnswer')
? You may also want to heed the warning under the example from that link: WARNING: This feature should rarely be required for regular clean code! Leave it for legacy code. Mocking a mock to return a mock, to return a mock, (...), to return something meaningful hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).