I'm trying to write unit test for my service layer:
@SpringBootTest
class ClinicServiceTest {
@Mock
private ProcedureRepository procedureRepository;
@InjectMocks
private ClinicService clinicService;
@Test
void setProcedureStatus() {
when(procedureRepository.findById(1L)).thenReturn(Optional.of(initialEntity));
when(procedureRepository.saveAndFlush(expectedEntity)).thenReturn(expectedEntity);
Procedure assertProcedure = clinicService.setProcedureStatus(1L, "CANCELED");
}
}
When i call setProcedureStatus method it throws NullPointerException because my service class uses ModelMapper that is being autowired by Spring:
@Service
@RequiredArgsConstructor
public class ClinicService {
private final ProcedureRepository procedureRepository;
private final ModelMapper modelMapper;
public Procedure setProcedureStatus(Long procedureId, String status) {
...
return modelMapper.map(procedureEntity, Procedure.class);
}
}
Unit test doesn't raise Spring context, that's the reason why ModelMapper is null in Service when i call it from test. Is there ways to solve this problem?