jUnit如何使用@Test(expected = ...)

时间:2011-05-18 16:09:30

标签: java junit

我有这个方法:

public String getNum(int x) throws Exception
{
    if(x == 0) {
         throws new Exception("x cannot be 0");
    }
    ...
}

现在在我的JUnit测试中,我试试这个

@Test(expected=Exception.class)
public void testNum() {
     String x = getNum(0);
}

但Eclipse仍然希望我为String x = getNum(0);添加一个throws声明或环绕用try catch。我做错了什么?这个测试应该通过,因为我在传入0时预计会出现异常。

2 个答案:

答案 0 :(得分:4)

只需在throws的声明中添加testNum子句?

答案 1 :(得分:4)

只需添加throws声明Java编译器对已检查的异常所需的声明。在你的情况下,它只不过是声明:)

相关问题