I am writing unit test for my service layer by mocking the object behaviour using mockito
framework, and right now, I am stuck in the middle of NullPointerException
coming from one of my test, I have checked everything that needs to be checked but I can't seem to figure out why the test is failing.
I had this MockitoAnnotations.openMocks(this)
; at the beginning of the test before, If I take it off, another line in my test is throwing an exception, the exception is getting thrown as a result of the repository calling the actual database instead of the mocked object.
Cannot invoke "com.repository.CreatedRequestRepository.save(Object)" because "this.createdRequestRepository" is null java.lang.NullPointerException: Cannot invoke "com.repository.CreatedRequestRepository.save(Object)" because "this.createdRequestRepository" is null
Here is the failing test
@Test
public void creates_RequestTest() {
// MockitoAnnotations.openMocks(this);
Request requestWithServiceType = Request.builder()
.id(1L).name("Aliyah").requestType(RequestType.SERVICE)
.requestId("01278").requestStatus(RequestStatus.RECEIVED)
.deptStatus(Dept.UNASSIGNED).submittedOn(LocalDate.now()).build();
JSONObject jsonObject = new JSONObject();
when(requestRepository.findById(Mockito.eq(1L))).thenReturn(Optional.of(requestWithServiceType));
ApiResponse<?> response = requestServiceImpl.createRequest(jsonObject);
Assertions.assertThat(response.getMessage()).isEqualTo("1");
Assertions.assertThat(response.getDetails()).isNotNull();
verify(requestRepository).findById(1L);
}
the null pointer is coming from this method
@Override
public ApiResponse<?> createRequest(JSONObject data) {
JSONObject jsonObject = new JSONObject();
for (String key : data.keySet()) {
Object value = data.get(key);
jsonObject.put(key, value);
}
CreatedRequest createdRequest = CreatedRequest.builder()
.createdAt(LocalDateTime.now())
.fields(jsonObject)
.build();
CreatedRequest createdRequestId = createdRequestRepository.save(createdRequest); // this line is throwing the null pointer
return requestCreatedResponse(createdRequestId.getId(), jsonObject);
}
here is the top of the class
@Service
@AllArgsConstructor
public class RequestServiceImpl implements RequestService {
private final RequestRepository requestRepository;
private final CreatedRequestRepository createdRequestRepository;
}