Issue
I want to write tests for service, but it looks like JPARepository.save method returns null. Here is my code from ServiceTest
@ExtendWith(MockitoExtension.class)
class PatientServiceTest {
@Mock
private PatientRepository patientRepository;
@Spy
private PatientMapper mapper = new PatientMapper();
@InjectMocks
private PatientService serviceUnderTests;
@Test
void whenCreatePatientByService_thenPatientRepositoryIsNotEmpty() {
PatientModel patientModel = new PatientModel(134, "Pawel", "Nowak",
"[email protected]", "123456789");
serviceUnderTests.create(patientModel);
assertNotNull(patientRepository.findAll());
}
Service code
public PatientModel create(PatientModel patientModel) {
PatientEntity patientEntity = mapper.from(patientModel);
PatientEntity savedPatient = repository.save(patientEntity);
return mapper.from(savedPatient);
}
Here is a screenshot from debugging mode:
Repository is just interface extends JPARepository, and mapper has only two methods which map Entity to Model and Model to Entity.
IntelliJ says:
java.lang.NullPointerException: Cannot invoke "com.nowakpawel.healthcenter.repository.entity.PatientEntity.getId()" because "entity" is null
at com.nowakpawel.healthcenter.service.mapper.PatientMapper.from(PatientMapper.java:24)
at com.nowakpawel.healthcenter.service.PatientService.create(PatientService.java:29)
at com.nowakpawel.healthcenter.service.PatientServiceTest.whenCreatePatientByService_thenPatientRepositoryIsNotEmpty(PatientServiceTest.java:44)
Why when I want to map Entity to Model in Service, Java put null into from method, while PatientEntity isn't null?
Solution
PatientModel is passed as parameter to the method and it is converted into PatientEntity patientEntity object. As its a unit test and the PatientRepository has been mocked, so when something is mocked you need to return the value of the mock.
So value should be returned for the statement
PatientEntity savedPatient = repository.save(patientEntity);
You can write the test case in this way
void whenCreatePatientByService_thenPatientRepositoryIsNotEmpty() {
PatientModel patientModel = new PatientModel(134, "Pawel", "Nowak",
"[email protected]", "123456789");
PatientEntity patientEntity = new PatientEntity();
patientEntity.setXxxx("Nowak"); // Other values as per getter and setters
doReturn(patientEntity).when(patientRepository).save(Matchers.any());
PatientModel response = serviceUnderTests.create(patientModel);
assertNotNull(response);
asserEquals("Nowak", response.getXxxxx()); //Getter method name here
}
Answered By - Tris
Answer Checked By - Pedro (JavaFixing Volunteer)