为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕少森 2021-07-12 13:07:29
我有这个方法要在 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,    []);
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 326 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信