[英]Is there a way for a JUnit test to pass iff method implementation is correct AND recursive?
[英]Correct way to JUnit test divide() method
我有这个简单的方法:
public int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by 0");
} else {
return a / b;
}
}
我想对 JUnit 进行测试。
我做了如下:
@Test(expected = ArithmeticException.class) // Expected this exc
public void testDivideWhenDivisorIsZero() {
int result = c.divide(1, 0);
}
它“返回”一条绿色条线(“测试成功完成”)。
try-catch
子句?编辑
此 JUnit 测试是否与以下测试等效?
@Test
public void testDivideWhenDivisorIsZero() {
try{
c.divide(1, 0);
fail("Expected ArithmeticException");
} catch(ArithmeticException e) {
}
}
你的测试看起来是正确的,你不应该在单元测试中使用try..catch
块。 有很多方法,其中一种是你的。 但是对于您的方法,我想使用:
try {
return a / b;
} catch (ArithmeticException e) {
throw new ArithmeticException("Division by 0");
}
让异常被抛出,并捕获它。 它比在任何操作之前检查值更干净(这种情况很少发生)
你这样做的方式对我来说似乎很好。
在这种情况下,它应该适合您的需要。 尽管如此,我个人更喜欢使用 try-catch-block 来完成。 正如你所提议的,这非常等价。 我认为如果你使用 try-catch-block 会有一些优势。
首先,您可以断言,如果抛出的异常的错误消息实际上与您已排除的一样,而且您可以确定该异常实际上是在您的被测方法期间发生的,而不是在您的初始化逻辑期间发生的。 为了更清楚一点:
public int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by 0");
} else if(a<b){
//I know, that this condition is pretty senseless. It's for demonstration only.
throw new ArithmeticException("a is smaller than b");
} else{
return a / b;
}
}
然后您可以像这样测试您的方法,并且可以确定抛出了正确的异常:
@Test
public void testDivideWhenDivisorIsZero() {
try{
c.divide(1, 2);
fail("Expected ArithmeticException");
} catch(Exception e) {
if(e instanceof ArithmeticException){
Assert.assertTrue(e.getMessage().equals("a is smaller than b"));
}else{
fail("The wrong Exception was thrown" + e.toString())
}
}
}
但正如我所说,您的尝试完全符合需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.