Mockito 注入模拟 Spring 启动测试

Mockito injecting mocks Spring Boot test

您好,我有一个包含映射器和存储库的服务 class:

@Service
public class ProductServiceImp implements ProductService {
    @Autowired
    private ProductRepository repository;
    @Autowired
    private WarehouseApiMapper mapper;

    public ProductServiceImp(ProductRepository repository) {
        this.repository = repository;
    }
}

存储库:

@Repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
}

映射器:

@Mapper(componentModel = "spring")
public interface WarehouseApiMapper {
    WarehouseApiMapper mapper = Mappers.getMapper(WarehouseApiMapper.class);

    Product ProductDtoToProduct(ProductDto productDto);

    ProductDto ProductToProductDto(Product product);
}

在测试中 class 我想注入模拟存储库和自动装配映射器 这是我的测试 class:

@SpringBootTest
public class ProductServiceTest {

    @Mock
    ProductRepository repository;

    @InjectMocks
    ProductServiceImp service;

    @ParameterizedTest
    @MethodSource("provideParametersProductUpdate")
    void assert_that_product_is_updated_correctly(String productName, BigDecimal productPrice) {
        Product oldProduct = new Product("Product that does not exist", BigDecimal.valueOf(1000000), null);
        oldProduct.setId(1);
        Mockito.when(repository.findById(1)).thenReturn(Optional.of(oldProduct));

        Product newProduct = new Product(productName, productPrice, null);
        newProduct.setId(1);
        ProductDto updatedProduct = service.updateProduct(newProduct);

        Assertions.assertEquals(productPrice, updatedProduct.getPrice());
        Assertions.assertEquals(productName, updatedProduct.getName());
    }

    private static Stream<Arguments> provideParametersProductUpdate() {
        return Stream.of(
                Arguments.of("dark chocolate", BigDecimal.valueOf(3.2)),
                Arguments.of("chewing gum", BigDecimal.valueOf(1.2)),
                Arguments.of("lollipop", BigDecimal.valueOf(4.0))
        );
    }
}

尝试在服务方法中映射对象时代码抛出 NullPointerException。 有人知道我怎么能注射这个?感谢您的回答

如果您只想创建一个 Mockito 测试,您可以使用注释 @RunWith(MockitoJUnitRunner.class) 而不是 @SpringBootTest

但是如果你想创建一个 Spring 引导集成测试,那么你应该使用 @MockBean 而不是 @Mock@Autowired 而不是 @InjectMocks