JUnit Eclipse检查是否抛出异常?

时间:2014-12-18 19:47:31

标签: eclipse junit

嘿伙计们,我有这个针对factorial的Junit测试代码

@org.junit.Test
public void testIterationAAA()
{
    Iteration test = new Iteration("AAA");
    int result = test.factorial("AAA");

    assertEquals("exceptionMessage",result);

}

据说因为字符串的阶乘不能被计算出来我应该抛出异常但是如何使用Junit测试它?

2 个答案:

答案 0 :(得分:0)

import org.junit.Assert;

...

@org.junit.Test
public void testIterationAAA()
{
    try {
         Iteration test = new Iteration("AAA");
         int result = test.factorial("AAA");
         // The above line is expected to throw an exception.
         // If the code does not throw an exception, fail the test.
         Assert.fail("An exception should have been thrown");
    } catch (Exception ex) {
         // Nothing to do.  Exception was expected in this test case.
    }

}

答案 1 :(得分:0)

您应该使用expected属性

@Test(expected=SomeException.class)