簡體   English   中英

單元測試中的映射器返回 null

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM