我知道有一种方法是:

@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?)


当前回答

对于5之前的JUnit版本:

使用AssertJ fluent断言3.7.0:

Assertions.assertThatCode(() -> toTest.method())
    .doesNotThrowAnyException();

更新:

JUnit 5引入了assertDoesNotThrow()断言,所以我更喜欢使用它,而不是向项目添加额外的依赖项。详情请看这个答案。

其他回答

你可以使用@Rule,然后调用方法reportMissingExceptionWithMessage,如下所示: 这是Scala代码。

对于5之前的JUnit版本:

使用AssertJ fluent断言3.7.0:

Assertions.assertThatCode(() -> toTest.method())
    .doesNotThrowAnyException();

更新:

JUnit 5引入了assertDoesNotThrow()断言,所以我更喜欢使用它,而不是向项目添加额外的依赖项。详情请看这个答案。

虽然这篇文章已经发布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新版本的人

AssertJ可以处理这种情况:

assertThatNoException().isThrownBy(() -> System.out.println("OK"));

查看文档了解更多信息https://assertj.github.io/doc/#assertj-core-exception-assertions-no-exception

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));
    }

}