【问题标题】:Mockito injecting mocks Spring Boot testMockito 注入模拟 Spring Boot 测试
【发布时间】:2021-05-28 23:37:39
【问题描述】:

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

@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。 有人知道我怎么注射这个吗?谢谢你的回答

【问题讨论】:

    标签: spring-boot dependency-injection mocking mockito spring-boot-test


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2021-01-26
      相关资源
      最近更新 更多