我正在尝试创建一个名为 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 的一个实例和异常消息字符串包含“包中没有物品!”)
我不确定为什么会这样……特别是因为我的预期错误消息确实正确打印到了控制台。在此先感谢您的帮助!