I have service method which return mapper to convert entity to DTO when I run the application everything work successfully but when I do unit test the mapper return null. Also I should mention that, this service is being called by another service "customerDetails" which is under the test.
code snippet, I put comments to describe the problem more :
customerService
public class customerService {
private final CustomerMapper customerMapper;
public Customer customerDetails(int id) {
CustomerDto customer = getById(id) //here is the problem customer is null
// rest of the code
}
public CustomerDto getById(int id) {
Optional<Customer> customer =
this.customerRepository.findCustomerByIdAndIsDeletedFalse(id); //assessment is filled successfully
return this.customerMapper.map(customer.get()); //the mapper her return customerDto and accept customer and it return null in unit test only
}
}
customerServiceTest
public class CustomerServiceTest {
@Mock
private CustomerRepository customerRepository;
@InjectMocks
private CustomerService customerService;
@BeforeEach
public void createMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCustomerDetails() {
Customer expectedResponse = DummyCustomer.create();
when(customerRepository.findCustomerByIdAndIsDeletedFalse(actualResponse.getId()).thenReturn(Optional.of(expectedResponse));
Customer response = this.CustomerService.customerDetails(expectedResponse.getId());
}
}
In actual code Spring handles injection of your mapper for you - but in unit test you don't have spring context set up. In fact you'd have seen the issue earlier if instead of relying on @InjectMocks
you tried to initialize the service manually.
As to solutions - in test code you can get an instance of your mapper using org.mapstruct.factory.Mappers.getMapper()
method. Use it and set it in your service under test properly (however you inject your dependencies - via constructor or setter). Or, if you want a "pure" unit test of just one component, mock it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.