public class Calculator
{
public int divide(int a, int b) throws Exception{
if(0==b){
throw new Exception("除数不能为0");
}
return a/b;
}
}
这里我们在CalculatorTest里面要测试这个异常的抛出。
@Test
public void testDivideByZero(){
Throwable th=null;
try
{
cal.divide(4, 0);
fail();
}
catch (Exception e)
{
th=e;
e.printStackTrace();
}
assertEquals(Exception.class, th.getClass());
assertEquals("除数不能为0", th.getMessage());
}
在这里声明一个Throwable类的对象th, 由于Throwable是Exception的父类,所以在catch语句中, 我们可以将th指向e的引用。
最后测试Exception.class和th.getClass()是否是同一个运行中的类,
然后测试message是否相同。
这个是junit3的测试方法。 junit4就特别简单了。
通过注释的方法
@Test(expected=Exception.class)
然后去掉try/catch那一堆, 就可以了。