![](/img/trans.png)
[英]model mapper mock returns null object in spring boot unit test
[英]mapper in unit test is return null
我有服务方法,当我运行应用程序时,它返回映射器以将实体转换为 DTO,但当我进行单元测试时,映射器返回 null。 另外我应该提到的是,该服务正在被另一个正在测试的服务“customerDetails”调用。
代码片段,我把评论更多地描述了这个问题:
客户服务
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
}
}
客户服务测试
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());
}
}
在实际代码中,Spring 为您处理映射器的注入 - 但在单元测试中,您没有设置 spring 上下文。 事实上,如果您尝试手动初始化服务而不是依赖@InjectMocks
,那么您早就看到了这个问题。
至于解决方案 - 在测试代码中,您可以使用org.mapstruct.factory.Mappers.getMapper()
方法获取映射器的实例。 使用它并在你的服务中正确设置它(但是你注入你的依赖项 - 通过构造函数或设置器)。 或者,如果您想要仅对一个组件进行“纯”单元测试,请模拟它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.