JUnit测试divide()方法的java正确方法
我有一个简单的方法:
public int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by 0");
} else {
return a / b;
}
}
我想测试一下
我做了如下工作:
@Test(expected = ArithmeticException.class) // Expected this exc
public void testDivideWhenDivisorIsZero() {
int result = c.divide(1, 0);
}
“返回”绿色条线(“测试成功完成”)
- 这是JUnit测试此方法的正确方法,还是应该在该测试中放入
try-catch
子句李>
编辑
这个JUnit测试是否等同于以下测试
@Test
public void testDivideWhenDivisorIsZero() {
try{
c.divide(1, 0);
fail("Expected ArithmeticException");
} catch(ArithmeticException e) {
}
}
# 1 楼答案
生产代码: 捕获或声明异常都不是必需的,我建议避免两者
如果您想与您的API用户通信可以抛出算术异常,那么您应该在javadoc中这样做
测试代码: JUnit5使asserting exceptions更加容易
# 2 楼答案
您的测试看起来是正确的,您不应该在单元测试中使用
try..catch
块。有很多方法,其中一种是你的。但对于您的方法,我想使用:让异常被抛出,并捕获它。它比在任何操作之前检查值更干净(这种情况很少发生)
# 3 楼答案
我觉得你这样做很好
在这种情况下,它应该适合你的需要。尽管如此,我个人还是更喜欢用try-catch块。正如你所建议的,这是相当等价的。我认为如果你使用try-catch块,你会有一些优势
首先,如果抛出异常的errormessage实际上与您所预期的一样,并且您可以确定异常确实发生在您的测试方法期间,而不是在您的初始化逻辑期间,那么您可以断言。 要让这一点更清楚一点:
然后,您可以像这样测试您的方法,并且可以确保抛出了正确的异常:
但正如我所说,你的尝试完全符合需要