【问题标题】:Write own exception in logger在记录器中写入自己的异常
【发布时间】:2018-10-13 17:03:45
【问题描述】:

有在数组中插入元素的方法。

  public boolean insertElementToSlot(Element element, int index) {
        checkArray(index);
        try {
            if (element != null && mas[index] == null) {
                mas[index] = element;
                return true;
            } else {
               throw  new ElementValidationException("Element.insertElementToSlot", device);
            }
        } catch (ElementValidationException d) {
            logger.log(Level.SEVERE, ""+d);
        }

        return false;
    }

并拥有带有方法的异常类:

public ElementValidationException(String operation, Element element) {
        super("Element is not valid for operation" + checkOperation(operation));
        this.element = element;
    }

在测试方法insertElementToSlot时,我有错误

java.lang.AssertionError: Expected exception: com.inventory.exception.ElementValidationException

为什么会出现错误以及如何解决?

【问题讨论】:

  • @Test 中有 expected 子句吗?如果是,如果您不希望测试抛出异常,请将其删除。

标签: java exception logging


【解决方案1】:

如果您有一个单元测试预期会出现异常,则必须将其从测试中剔除。它不检查这个异常是否在代码中的任何地方抛出但被捕获。

注意:您的异常没有被用作异常,可以用日志消息替换

你的代码基本一样

public boolean insertElementToSlot(Element element, int index) {
    checkArray(index);
    if (element != null && mas[index] == null) {
          mas[index] = element;
          return true;
    }
    logger.log(Level.SEVERE, "some.package.ElementValidationException");
    return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 2010-10-20
    • 2016-04-08
    • 1970-01-01
    相关资源
    最近更新 更多