单元测试引发异常

时间:2019-05-23 21:54:51

标签: java junit mockito

我正在尝试对负责返回给定产品脂肪数量的单元测试方法。

public class NutrientsCalculationService {

    ....

    double countFatNumberOfGivenProduct(UserProduct productToCalculate) {
        double fatNumber = retrieveGivenProductFromDB(productToCalculate).getFatNumber(); // All given data in DB are per 100g!!!
        return (fatNumber * productToCalculate.getGram()) / ONE_HUNDRED_GRAMS;
    }


    Product retrieveGivenProductFromDB(UserProduct productToCalculate) {
        if (productToCalculate.getGram() > 0) {
            return productRepository.findByName(productToCalculate.getName())
                    .orElseThrow(() -> new IllegalArgumentException("Product does not exist!"));
        } else {
            throw new IllegalArgumentException("Grams can not be negative");
        }
    }

我试图为此编写一个单元测试,但是它抛出异常,表明该产品不存在。在此测试中我应该更改什么?

@RunWith(MockitoJUnitRunner.class)
public class NutrientsCalculationServiceTest {

    @Mock
    private ProductRepository productRepository;
    @Mock
    private AccountRepository accountRepository;

    @InjectMocks
    private NutrientsCalculationService nutrientsCalculationService;

    @Test
    public void countFatNumberOfGivenProduct() {
        UserProduct userProduct = createDummyUserProduct();
        Product product = createDummyProduct();
        //when(productRepository.findByName(userProduct.getName())).thenReturn(product);
        //when(nutrientsCalculationService.retrieveGivenProductFromDB(userProduct)).thenReturn(product);
        double expectedFatNumber = nutrientsCalculationService.countFatNumberOfGivenProduct(userProduct);
        double actualFatNumber = product.getFatNumber();

        assertEquals(expectedFatNumber, actualFatNumber,0.0002);
    }

    private UserProduct createDummyUserProduct() {
        return new UserProduct(1, "Schnitzel", 129, 4.2);
    }

    private Product createDummyProduct() {
        return new Product.ProductBuilder()
                .withName("Schnitzel")
                .withCarbohydratesNumber(0)
                .withFatNumber(4.2)
                .withProteinsNumber(22.9)
                .withKcal(129)
                .withType(ProductType.MEAT)
                .build();
    }
}

java.lang.IllegalArgumentException:产品不存在!

at trainingapp.calculations.NutrientsCalculationService.lambda$retrieveGivenProductFromDB$0(NutrientsCalculationService.java:51)
at java.base/java.util.Optional.orElseThrow(Optional.java:397)
at trainingapp.calculations.NutrientsCalculationService.retrieveGivenProductFromDB(NutrientsCalculationService.java:51)
at trainingapp.calculations.NutrientsCalculationService.countFatNumberOfGivenProduct(NutrientsCalculationService.java:29)
at trainingapp.calculations.NutrientsCalculationServiceTest.countFatNumberOfGivenProduct(NutrientsCalculationServiceTest.java:34)

1 个答案:

答案 0 :(得分:2)

在您的示例中,您已经创建了ProductRepository的Mock,但是您并没有真正说出在ProductRepository上调用方法时会发生什么。 编辑: 我刚刚注意到,如果您取消对此部分的评论,它将会正常工作。