gpt4 book ai didi

java - 使用 JUnit 进行单元测试时如何处理异常?

转载 作者:搜寻专家 更新时间:2023-11-01 04:02:09 24 4
gpt4 key购买 nike

如果一个方法抛出异常,如何编写测试用例来验证该方法是否确实抛出了预期的异常?

最佳答案

在最新版本的 JUnit 中,它是这样工作的:

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class NumberFormatterExceptionsTests {

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrowExceptionWhenDecimalDigitsNumberIsBelowZero() {
thrown.expect(IllegalArgumentException.class); // you declare specific exception here
NumberFormatter.formatDoubleUsingStringBuilder(6.9, -1);
}
}

关于 ExpectedExceptions 的更多信息:

http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html

http://alexruiz.developerblogs.com/?p=1530

// These tests all pass.
public static class HasExpectedException {
@Rule
public ExpectedException thrown= ExpectedException.none();

@Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}

@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}

@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}

关于java - 使用 JUnit 进行单元测试时如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184281/

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