单位测试引发异常



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

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)

在您的示例中,您创建了ProductRepository的模拟,但是当您在ProductRepository上调用方法时,您并没有真正说出应该发生什么。编辑:我刚刚注意到,如果您输入该部分,则该部分会被评论 - 它应该很好。

相关内容

  • 没有找到相关文章

最新更新