[英]mapper in unit test is return null
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.我有服务方法,当我运行应用程序时,它返回映射器以将实体转换为 DTO,但当我进行单元测试时,映射器返回 null。 Also I should mention that, this service is being called by another service "customerDetails" which is under the test.另外我应该提到的是,该服务正在被另一个正在测试的服务“customerDetails”调用。
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.在实际代码中,Spring 为您处理映射器的注入 - 但在单元测试中,您没有设置 spring 上下文。 In fact you'd have seen the issue earlier if instead of relying on @InjectMocks
you tried to initialize the service manually.事实上,如果您尝试手动初始化服务而不是依赖@InjectMocks
,那么您早就看到了这个问题。
As to solutions - in test code you can get an instance of your mapper using org.mapstruct.factory.Mappers.getMapper()
method.至于解决方案 - 在测试代码中,您可以使用org.mapstruct.factory.Mappers.getMapper()
方法获取映射器的实例。 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.或者,如果您想要仅对一个组件进行“纯”单元测试,请模拟它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.