永远不会在相应的try块中抛出异常

时间:2018-02-02 13:42:59

标签: java exception testing junit

我有这个方法:

public int addInt(int x, int y){
    try{
        if(x<1 || y<1){
            throw new InvalidValueExeption();
        }
    } catch(InvalidValueExeption i){
        System.out.println(i);
    }
    return x+y;
}

InvalidValueExeption是自定义异常。所以我想测试一下:

@Test
public void test(){
    AddClass a = new AddClass();
    boolean thrown = false;

    try{
        a.addInt(-2, 3);
    } catch(InvalidValueException e){
        thrown=true;
    }

    assertTrue(thrown);
}

我无法运行此测试,因为它显示Exception exception.InvalidValueException is never thrown in the corresponding try block

我做错了什么?

3 个答案:

答案 0 :(得分:1)

如果InvalidValueExeption是一个已检查的异常,那么编译器会抱怨,因为addInt未声明为 throw InvalidValueExeption

如果InvalidValueExeption不是已检查的例外,则测试将失败,因为addInt吞下了InvalidValueExeption

您的问题中也可能存在拼写错误:addInt()抛出InvalidValueExeptiontest()尝试抓住InvalidValueException。在前一种情况下,异常拼写为“Exeption”,在后一种情况下拼写为“Exception”,注意缺少“c”。

以下方法可行:

public int addInt(int x, int y) {
    if (x < 1 || y < 1) {
        throw new InvalidValueException();
    }

    return x + y;
}

@Test(expected = InvalidValueException.class)
public void test(){
    AddClass a = new AddClass();

    a.addInt(-2, 3);
}

答案 1 :(得分:0)

首先,我认为您的InvalidValueExeptionRuntimeException的子类型。

  

RuntimeException及其子类是未经检查的异常。   未经检查的异常不需要在方法中声明   构造函数的throws子句,如果它们可以被执行抛出   方法或构造函数并在方法或方法之外传播   构造函数边界。

因此,如果您需要指明您抛出InvalidValueExeption或继承Exception

此处异常在您的方法上声明并抛出:

public int addInt(int x, int y) throws InvalidValueExeption  {
     try {
        //..
         throw new InvalidValueExeption();
     } catch (InvalidValueExeption e) {
         // do some logging the throw back at you
         throw e;
     }
}

答案 2 :(得分:0)

您的addInt()方法不会抛出InvalidValueException(*)。在方法内部,你会抛出它,但是你可以在它可以离开之前抓住它#34;你的方法。因此,对于外部世界,您的方法没有InvalidValueException

然后,正确的编译器告诉你,抓住InvalidValueException没有意义。

因此,不是立即在方法中捕获异常,而是声明方法抛出InvalidValueException

public int addInt(int x, int y) throws InvalidValueException {
    if (x < 1 || y < 1) {
        throw new InvalidValueException();
    }
    return x + y;
}

<强>理由:

例外情况是告诉调用者(**)某些方法无法完成其任务,即您的addInt()方法旨在仅添加正数。如果有人尝试使用低于1的数字,该方法会回答异常,而不是返回一个值,因此说:&#34;嘿,出了点问题,所以我无法给你一个答案(而且问题描述是[其消息等的例外情况])。&#34;

(*)我假设,缺少&#34; c&#34;只是一个错字,你没有两个不同的异常类。

(**)这很重要。我不是在谈论System.out.println(),因为它告诉了用户,而不是来电