![]() |
年轻有为的双杠 · java junit mock跳过一行代码 ...· 2 周前 · |
![]() |
苦恼的荔枝 · Shell脚本使用jq解析json_shel ...· 11 月前 · |
![]() |
痴情的油条 · Azure 数据工厂中带分隔符的文本格式 ...· 1 年前 · |
![]() |
爽快的墨镜 · matlab怎么截取字符串-百度经验· 2 年前 · |
在JUnit 5中,有没有更好的方法来断言方法抛出了异常?
目前,我必须使用@Rule来验证我的测试是否抛出了异常,但这不适用于我期望在测试中有多个方法抛出异常的情况。
您可以使用
assertThrows()
,它允许您在同一个测试中测试多个异常。由于Java8对lambda的支持,这是在JUnit中测试异常的标准方法。
根据 JUnit docs
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
MyException thrown = assertThrows(
MyException.class,
() -> myObject.doThing(),
"Expected doThing() to throw, but it didn't"
assertTrue(thrown.getMessage().contains("Stuff"));
}
实际上,我认为这个特定示例的文档中存在错误。要使用的方法是expectThrows
public static void assertThrows(
public static <T extends Throwable> T expectThrows(
他们在JUnit 5中对其进行了更改(期望的: InvalidArgumentException,实际的:调用的方法),代码如下:
@Test
public void wrongInput() {
Throwable exception = assertThrows(InvalidArgumentException.class,
()->{objectName.yourMethod("WRONG");} );
}
您可以使用
assertThrows()
。我的例子取自文档的
http://junit.org/junit5/docs/current/user-guide/
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
assertEquals("a message", exception.getMessage());
}
我认为这是一个更简单的例子
List<String> emptyList = new ArrayList<>();
Optional<String> opt2 = emptyList.stream().findFirst();
assertThrows(NoSuchElementException.class, () -> opt2.get());
在包含空
ArrayList
的可选对象上调用
get()
将引发
NoSuchElementException
。
assertThrows
声明了预期的异常并提供了一个lambda提供者(不接受任何参数并返回值)。
感谢@prime的回答,我希望他的回答是详细的。
这里有一个简单的方法。
@Test
void exceptionTest() {
model.someMethod("invalidInput");
fail("Exception Expected!");
catch(SpecificException e){
assertTrue(true);
catch(Exception e){
fail("wrong exception thrown");
}
只有当您期望的异常被抛出时,它才会成功。
![]() |
爽快的墨镜 · matlab怎么截取字符串-百度经验 2 年前 |