'How to mock ModelMapper in Spring?

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?



Solution 1:[1]

If you are testing your modelmapper map returning values, you can use @Spy. Example using:

this way is preparing a modelmapper with default constructor.

@Spy
ModelMapper modelMapper;

or you can customize with builder or constructor a modelmapper or any other types with instance creation way.

@Spy
ModelMapper modelMapper=new ModelMapper();

Therefore when you use a @InjectMocks they will inject inside the service or related field.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 withoutOne