我知道有一种方法是:
@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?)
当前回答
使用assertNull(…)
@Test
public void foo() {
try {
//execute code that you expect not to throw Exceptions.
} catch (Exception e){
assertNull(e);
}
}
其他回答
用void方法来测试场景
void testMeWell() throws SomeException {..}
不抛出异常:
Junit5
assertDoesNotThrow(() -> {
testMeWell();
});
对于5之前的JUnit版本:
使用AssertJ fluent断言3.7.0:
Assertions.assertThatCode(() -> toTest.method())
.doesNotThrowAnyException();
更新:
JUnit 5引入了assertDoesNotThrow()断言,所以我更喜欢使用它,而不是向项目添加额外的依赖项。详情请看这个答案。
AssertJ可以处理这种情况:
assertThatNoException().isThrownBy(() -> System.out.println("OK"));
查看文档了解更多信息https://assertj.github.io/doc/#assertj-core-exception-assertions-no-exception
在这个问题上遇到了麻烦,因为我创建了一些泛型方法
@Test
void testSomething() {
checkGeneric(anComplexObect)
}
在https://newbedev.com/sonarqube-issue-add-at-least-one-assertion-to-this-test-case-for-unit-test-with-assertions中提出了一些注释的东西。
解决方案要简单得多。将“checkGeneric”方法重命名为“assertGeneric”就足够了。
@Test
void testSomething() {
assertGeneric(anComplexObect)
}
这可能不是最好的方法,但它肯定能确保不会从正在测试的代码块抛出异常。
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
}
}