我知道有一种方法是:
@Test
public void foo() {
try {
// execute code that you expect not to throw Exceptions.
} catch(Exception e) {
fail("Should not have thrown any exception");
}
}
还有更干净的方法吗?(可能使用了Junit的@Rule?)
我知道有一种方法是:
@Test
public void foo() {
try {
// execute code that you expect not to throw Exceptions.
} catch(Exception e) {
fail("Should not have thrown any exception");
}
}
还有更干净的方法吗?(可能使用了Junit的@Rule?)
当前回答
以下是所有检查或未检查的异常都无法通过测试:
@Test
public void testMyCode() {
try {
runMyTestCode();
} catch (Throwable t) {
throw new Error("fail!");
}
}
其他回答
用void方法来测试场景
void testMeWell() throws SomeException {..}
不抛出异常:
Junit5
assertDoesNotThrow(() -> {
testMeWell();
});
以下是所有检查或未检查的异常都无法通过测试:
@Test
public void testMyCode() {
try {
runMyTestCode();
} catch (Throwable t) {
throw new Error("fail!");
}
}
你可以使用@Rule,然后调用方法reportMissingExceptionWithMessage,如下所示: 这是Scala代码。
AssertJ可以处理这种情况:
assertThatNoException().isThrownBy(() -> System.out.println("OK"));
查看文档了解更多信息https://assertj.github.io/doc/#assertj-core-exception-assertions-no-exception
虽然这篇文章已经发布6年了,但是Junit世界已经发生了很多变化。现在可以使用Junit5
org.junit.jupiter.api.Assertions.assertDoesNotThrow()
Ex:
public void thisMethodDoesNotThrowException(){
System.out.println("Hello There");
}
@Test
public void test_thisMethodDoesNotThrowException(){
org.junit.jupiter.api.Assertions.assertDoesNotThrow(
()-> thisMethodDoesNotThrowException()
);
}
希望它能帮助那些正在使用Junit5新版本的人