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 ??
For injecting private fields in a public class, ReflectionTestUtils need to be used.
public class UserSshKeyServiceTest {
@InjectMocks
private UserSshKeyService userSshKeyService;
@Mock
private RecordEventService eventService;
@Mock
UserSshKeyRepository repository;
@Before
public void setup(){
ReflectionTestUtils.setField(userSshKeyService, "eventService", eventService);
ReflectionTestUtils.setField(userSshKeyService, "repository", repository);
}
}