@Test(expected=ArithmeticException.class)
public void testDivide() {
assertEquals(3,Math.divide(9,3));
Math.divide(10,0); //除数不能为0,会抛出异常
}
junit4中不用try catach了,用这样声明“@Test(expected=ArithmeticException.class)”Junit4就会检查此方法是否抛出ArithmeticException异常,
2)
套件方面
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({a.class,
b.class})
public class Util4Suite {
}
则a,b两个类都要运行测试
3) 参数化测试
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@RunWith(Parameterized.class)
public class SquareTest ...{
private static Calculator calculator = new Calculator();
private int param;
private int result;
@Parameters
public static Collection data() ...{
return Arrays.asList(new Object[][]...{
...{2, 4},
...{0, 0},
...{-3, 9},
});
}
//构造函数,对变量进行初始化
public SquareTest(int param, int result) ...{
this.param = param;
this.result = result;
}
@Test
public void square() ...{
calculator.square(param);
assertEquals(result, calculator.getResult());
}
}