猿问

如何计算使用 Junit 和 Mockito 调用方法的次数?

我有这个方法要在 ProductService 中测试:


@Override

    public void validateUpdate(Product product, Product modifiedProduct, List<FieldError> errors) throws AppException {

        if(modifiedProduct == null || product == null) {

            addError(errors, "product", "Product cannot be null");

        }else {

            validateName(modifiedProduct.getName(), errors);

            validateShortDescription(modifiedProduct.getShortDescription(), errors);

            validateDescription(modifiedProduct.getDescription(), errors);

            validateRegularPriceAndPromotionprice(modifiedProduct.getRegularPrice(), modifiedProduct.getPromotionPrice(), errors);

            validateCategory(product.getCategory(), errors);

            validateCategoryMatches(product.getCategory(), modifiedProduct.getCategory(), errors);

            validateStore(product.getStore(), errors);

            validateSku(modifiedProduct.getSku(), errors);

            validateWeight(modifiedProduct.getWeight(), errors);

            validateQuantityInStock(modifiedProduct.getQuantityInStock(), errors);

            validateNotifyLowStock(modifiedProduct.getNotifyLowStock(), errors);

        }

    }

但我只想创建一个测试来验证是否正在调用所有方法。第一个是查看 addError 方法是否被调用一次:


@Test

    public void testValidateUpdateProduct() {

        ProductService productService = Mockito.mock(ProductService.class);

        List<FieldError> errors = new ArrayList<FieldError>();

        productService.validateUpdate(null, null, errors);

        Mockito.verify(productService, Mockito.times(1)).addError(errors, "product", "Product cannot be null");

    }

但后来我得到:


Wanted but not invoked:

productService.addError(

    [],

    "product",

    "Product cannot be null"

);

-> at ca.edooby.edoobyapi.service.ProductServiceTest.testValidateUpdateProduct2(ProductServiceTest.java:1022)


However, there was exactly 1 interaction with this mock:

productService.validateUpdate(

    ca.edooby.edoobyapi.model.Product@d2ca3a9,

    ca.edooby.edoobyapi.model.Product@2b26d289,

    []

);


慕少森
浏览 327回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答