0

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 ??

1
  • 1
    Have you tried @Mock(answer = RETURNS_DEEP_STUBS) with when(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).
    – Morfic
    Commented May 21 at 13:29

1 Answer 1

0

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);
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.