我正在用JUnit练习,这是我想测试的简单方法
public float divide(int a, int b){
return (float)a/(float)b;
}
这是测试(Maths 只是我的一个包含该方法的自定义类):
@Test(expected = ArithmeticException.class )
public void divideByZeroShouldBeDetected(){
Maths m = new Maths();
m.divide(2,0);
}
无论如何运行这个测试都会导致失败...
编辑: 好的,刚刚检查了一些“奇怪”的东西,这段代码实际上给了我异常(exception):
float c = 2/0;
不管怎样,这个:
m.divide(2,0);
给我
Infinity
这就是测试失败的原因。那么..如何在 Junit 中测试这种行为?
最佳答案
好的解决了....问题是关于参数的类型,在这篇文章中你可以找到完整的解释Java division by zero doesnt throw an ArithmeticException - why? .
为了进行测试,我只需要断言返回值是“无限”,这样:
@Test
public void divideByZeroShouldBeDetected(){
Maths m = new Maths(2, 0);
assertEquals("divide float by zero should be infinity", true, Float.isInfinite(m.divide()));
}
关于java - JUnit 不检测 ArithmeticException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25621946/