我知道有一种方法是:
@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?)
当前回答
这可能不是最好的方法,但它肯定能确保不会从正在测试的代码块抛出异常。
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class AssertionExample {
@Test
public void testNoException(){
assertNoException();
}
private void assertException(){
Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
}
private void assertNoException(){
Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
}
private void doNotThrowException(){
//This method will never throw exception
}
}
其他回答
你可以使用@Rule,然后调用方法reportMissingExceptionWithMessage,如下所示: 这是Scala代码。
用void方法来测试场景
void testMeWell() throws SomeException {..}
不抛出异常:
Junit5
assertDoesNotThrow(() -> {
testMeWell();
});
我遇到了同样的情况,我需要检查异常是否在应该抛出的时候抛出,并且仅在应该抛出的时候抛出。 最终使用异常处理程序对我的好处如下代码:
try {
functionThatMightThrowException()
}catch (Exception e){
Assert.fail("should not throw exception");
}
RestOfAssertions();
对我来说,主要的好处是它非常直截了当,并且在相同的结构中检查“如果且仅当”的另一种方式非常容易
以下是所有检查或未检查的异常都无法通过测试:
@Test
public void testMyCode() {
try {
runMyTestCode();
} catch (Throwable t) {
throw new Error("fail!");
}
}
JUnit 5 (Jupiter)提供了三个函数来检查异常是否存在:
● 断言全部()
断言所有提供的可执行文件 不要抛出异常。
● assertDoesNotThrow()
类的执行 提供可执行/供应商 不抛出任何类型的异常。
此函数可用 JUnit 5.2.0以来(2018年4月29日)。
●assertThrows ()
断言所提供的可执行文件的执行 抛出expectedType的异常 并返回异常。
例子
package test.mycompany.myapp.mymodule;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw() {
String myString = "this string has been constructed";
assertAll(() -> MyClass.myFunction(myString));
}
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
String myString = "this string has been constructed";
assertDoesNotThrow(() -> MyClass.myFunction(myString));
}
@Test
void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
String myString = null;
assertThrows(
IllegalArgumentException.class,
() -> MyClass.myFunction(myString));
}
}