gpt4 book ai didi

java - junit中如何处理异常

转载 作者:行者123 更新时间:2023-11-30 12:02:16 25 4
gpt4 key购买 nike

我写了一些测试用例来测试一些方法。但是有些方法会抛出异常。我做得对吗?

private void testNumber(String word, int number) {
try {
assertEquals(word, service.convert(number));
} catch (OutOfRangeNumberException e) {
Assert.fail("Test failed : " + e.getMessage());
}
}

@Test
public final void testZero() {
testNumber("zero", 0);
}

如果我通过 -45,它将失败并返回 OutOfRangeException 但我无法测试特定异常,例如 @Test(Expected...)

最佳答案

意外异常是测试失败,因此您既不需要也不想捕获它。

@Test
public void canConvertStringsToDecimals() {
String str = "1.234";
Assert.assertEquals(1.234, service.convert(str), 1.0e-4);
}

直到 service 没有抛出 IllegalArgumentException 因为 str 中有一个小数点,那将是一个简单的测试失败。

预期异常应该由@Test 的可选expected 参数处理。

@Test(expected=NullPointerException.class)
public void cannotConvertNulls() {
service.convert(null);
}

如果程序员懒惰并抛出Exception,或者如果他让service返回0.0,测试将失败。只有 NPE 才会成功。请注意,预期异常的子类也有效。这在 NPE 中很少见,但在 IOExceptionSQLException 中很常见。

在极少数情况下,您想要测试特定的异常消息,您可以使用新的 ExpectedException JUnit @Rule

@Rule
public ExpectedException thrown= ExpectedException.none();
@Test
public void messageIncludesErrantTemperature() {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("-400"); // Tests that the message contains -400.
temperatureGauge.setTemperature(-400);
}

现在,除非 setTemperature 抛出 IAE 并且消息包含用户试图设置的温度,否则测试失败。可以以更复杂的方式使用此规则。


您的示例最好由以下人员处理:

private void testNumber(String word, int number)
throws OutOfRangeNumberException {
assertEquals(word, service.convert(number));
}

@Test
public final void testZero()
throws OutOfRangeNumberException {
testNumber("zero", 0);
}

你可以内联testNumber;现在,它没有多大帮助。您可以将其转换为参数化测试类。

关于java - junit中如何处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58719327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com