spring-boot - Mockito 注入模拟 Spring Boot 测试
问题描述
您好我有一个包含映射器和存储库的服务类:
@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);
}
在测试类中,我想注入模拟存储库和自动装配映射器这是我的测试类:
@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 Boot 集成测试,那么你应该使用@MockBean
代替@Mock
和@Autowired
代替@InjectMocks
.