Mockito injecting mocks Spring Boot test
Asked Answered
D

1

8

Hi I have a service class that contains mapper and repository:

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

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

Repository:

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

Mapper:

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

    Product ProductDtoToProduct(ProductDto productDto);

    ProductDto ProductToProductDto(Product product);
}

In test class I would like to inject mock repository and autowired mapper Here is my test 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))
        );
    }
}

Code throws NullPointerException when is trying to map object in service method. Somebody knows how can I inject this? Thanks for ur answers

Deucalion answered 26/2, 2021 at 15:18 Comment(0)
T
16

If you want to create just a Mockito test you could use the annotation @RunWith(MockitoJUnitRunner.class) instead of @SpringBootTest.

But if you want to create a Spring Boot integration test then you should use @MockBean instead of @Mock and @Autowired instead of @InjectMocks.

Ticonderoga answered 26/2, 2021 at 15:32 Comment(2)
@RunWith(MockitoJUnitRunner.class) doesn't work in Junit 5, thoughYuhas
For Junit 5 you can use @ExtendWith(MockitoExtension.class).Flattish

© 2022 - 2024 — McMap. All rights reserved.