2

我正在尝试创建一个名为 bag 的抽象数据类型,它本质上使用方法 add(int x) 接收整数,并使用方法 remove() 删除任意整数。

然后,我尝试为 remove() 方法创建一个自定义异常,因为当包中已经没有任何物品时,有可能完成删除。因此,我创建了一个异常类:

public class EmptyBagException extends Exception {
    public EmptyBagException(String message) {
        super(message);
    }
}

并继续使用此自定义异常,如下所示:

public int remove() {

    try {
        this.realRemoval();
    } catch (EmptyBagException e){
        System.out.println(e.getMessage());
    }

    return -1;
}

public int realRemoval() throws EmptyBagException {

    if (counter == 0) {
        throw new EmptyBagException("There are no items in the bag!");
    } else {
        ...
    }
}

然后,我尝试通过这样做来测试异常:

@Rule
public ExpectedException thrown = ExpectedException.none(); 

@Test
public void testThree() {

    IBag myBag = new BasicBag();
    myBag.remove();
    thrown.expect(EmptyBagException.class);
    thrown.expectMessage("There are no items in the bag!");

}

不幸的是,这个测试失败了,我得到了消息:

java.lang.AssertionError: Expected test to throw(sg.com.practice.adt.EmptyBagException 的一个实例和异常消息字符串包含“包中没有物品!”)

我不确定为什么会这样……特别是因为我的预期错误消息确实正确打印到了控制台。在此先感谢您的帮助!

4

1 回答 1

3

这是因为您实际上并没有将异常抛出remove()

public int remove() {

    try {
        this.realRemoval();
    } catch (EmptyBagException e){
        System.out.println(e.getMessage());
    }

    return -1;
}

在这种情况下,您的块realRemoval()会捕获并处理来自的异常。try...catch异常被抛出realRemoval()然后被你的处理程序捕获,消息被打印出来,就是这样:异常不会被重新抛出,而是返回-1。

如果您希望它重新抛出异常,则必须这样做:

public int remove() throws EmptyBagException { // <-- declare throws

    try {
        this.realRemoval();
    } catch (EmptyBagException e){
        System.out.println(e.getMessage());
        throw e; // <-- rethrow
    }

    return -1;

}

或者只是摆脱您的输出消息并让它自然发生:

public int remove() throws EmptyBagException { // <-- declare throws

    this.realRemoval(); // <-- may throw

    return -1;

}

另请注意,您需要在调用测试函数thrown 之前remove()进行设置,就像remove()抛出一样,然后测试函数将抛出并且实际上不会超过该点来设置thrown

顺便说一句,您不是要返回值realRemoval()而不是-1吗?

于 2017-02-22T03:38:38.517 回答