Spring 测试映射器返回 Null

问题描述 投票:0回答:1

我正在为我的后端项目编写测试单元。我还使用 ModelMapper 来实现地图功能。但是当我在管理器 ProductManager 的测试方法中编写 getAll() 或 update() 等时,Spring 说

org.modelmapper.ModelMapper.map(Object, java.lang.Class)”因为“hakan.productData.core.utilities.mappers.ModelMapperService.forRequest()”的返回值为null

我没搞清楚。你能帮我吗?

产品经理=

@Service
@AllArgsConstructor
@Transactional
public class ProductManager implements ProductService {

    private ProductRepository productRepository;
    private ProductBusinessRules productBusinessRules;
    private ModelMapperService modelMapperService;


    @Override
    @Transactional(readOnly = true)
    public List<GetAllProductsResponse> getAll() {
        List<Product> products = productRepository.findAll();
        List<GetAllProductsResponse> productsResponse= products.stream()
                .map(product -> this.modelMapperService.forResponse().map(product, GetAllProductsResponse.class)).collect(Collectors.toList());
        return productsResponse;
    }

    @Override
    public void add(CreateProductRequest createProductRequest) {
        this.productBusinessRules.checkIfProductNameExists(createProductRequest.getName());
        Product product = this.modelMapperService.forRequest().map(createProductRequest,Product.class);
        this.productRepository.save(product);
    }

    @Override
    public UpdateProductRequest update(UpdateProductRequest updateProductRequest) {
        Product product = this.modelMapperService.forRequest().map(updateProductRequest,Product.class);
        this.productRepository.save(product);
        return updateProductRequest;
    }

模型映射器管理器=

@Service
@AllArgsConstructor
public class ModelMapperManager implements ModelMapperService {
    private ModelMapper modelMapper;
    @Override
    public ModelMapper forResponse() {
        this.modelMapper.getConfiguration()
                .setAmbiguityIgnored(true)
                .setMatchingStrategy(MatchingStrategies.LOOSE);
        return this.modelMapper;
    }

    @Override
    public ModelMapper forRequest() {
        this.modelMapper.getConfiguration()
                .setAmbiguityIgnored(true)
                .setMatchingStrategy(MatchingStrategies.STANDARD);
        return this.modelMapper;
    }
}

产品经理测试=

@ExtendWith(MockitoExtension.class)
public class ProductManagerTest {


    @Mock
    private ProductRepository productRepository;
    @Mock
    private ProductBusinessRules productBusinessRules;
    @Mock
    private ModelMapperService modelMapperService;
    @Mock
    private ModelMapperManager modelMapper;

    @InjectMocks
    private ProductManager productManager;

    @Test
    @DisplayName("Should Find Post By Id")
    void shouldFindPostById() {
        Product product = new Product(123,"Milk","Drink",10,true,5);
        GetAllProductsResponse expectedProductResponse = new GetAllProductsResponse(123,"Milk","Drink",10,true,5);
        Mockito.when(productRepository.findById(123)).thenReturn(Optional.of(product));

        Optional<Product> actualPostResponse = productManager.getById(123);

        assertThat(actualPostResponse.get().getId()).isEqualTo(expectedProductResponse.getId());
        assertThat(actualPostResponse.get().getName()).isEqualTo(expectedProductResponse.getName());
        System.out.println("Test was successful");
    }

       @Test
       @DisplayName("Should Update By If")
       void shouldUpdateById(){

           Product product = Product.builder()
                   .name("Milk")
                   .category("Drink")
                   .price(10)
                   .quantity(10)
                   .onOffer(true)
                   .build();

           UpdateProductRequest getAllProductsResponse = UpdateProductRequest.builder()
                   .id(1)
                   .name("Coke")
                   .category("Drink")
                   .price(5)
                   .quantity(10)
                   .onOffer(true)
                   .build();
           when(productRepository.save(Mockito.any(Product.class))).thenReturn(product);
           when(productRepository.findById(0)).thenReturn(Optional.ofNullable(product));
           UpdateProductRequest updatedProduct = productManager.update(getAllProductsResponse);
           assertThat(updatedProduct).isNotNull();


       }

}

shouldFindPostById 测试方法工作正常,因为我没有使用任何映射器方法,但其他方法不起作用。

java spring-boot mockito spring-test modelmapper
1个回答
0
投票

我认为你的问题是你尝试在测试类中模拟

interface ModelMapperService
,但你没有模拟
class ModelMapperManager
。这意味着当您调用方法
modelMapperService.forRequest()
时,它会返回
null
值。

更新代码:

@ExtendWith(MockitoExtension.class)
public class ProductManagerTest {

    @Mock
    private ProductRepository productRepository;
    
    @Mock
    private ProductBusinessRules productBusinessRules;

    @Mock
    private ModelMapperManager modelMapperManager;

    @Mock
    private ModelMapper modelMapper;

    @InjectMocks
    private ProductManager productManager;

    @Test
    @DisplayName("Should Update By If")
    void shouldUpdateById() {
        Product product = Product.builder()
                .name("Milk")
                .category("Drink")
                .price(10)
                .quantity(10)
                .onOffer(true)
                .build();

        UpdateProductRequest updateProductRequest = UpdateProductRequest.builder()
                .id(1)
                .name("Coke")
                .category("Drink")
                .price(5)
                .quantity(10)
                .onOffer(true).build();

        when(modelMapperManager.forRequest()).thenReturn(modelMapper);
        when(productRepository.save(Mockito.any(Product.class))).thenReturn(product);
        when(productRepository.findById(0)).thenReturn(Optional.ofNullable(product));

        UpdateProductRequest updatedProduct = productManager.update(updateProductRequest);

        assertThat(updatedProduct).isNotNull();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.