我知道有一种方法是:

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


当前回答

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

其他回答

对于5之前的JUnit版本:

使用AssertJ fluent断言3.7.0:

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

更新:

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

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

我偶然发现这一点是因为SonarQube的规则“squid:S2699”:“向这个测试用例添加至少一个断言。”

我有一个简单的测试,它的唯一目标是不抛出异常。

考虑这段简单的代码:

public class Printer {

    public static void printLine(final String line) {
        System.out.println(line);
    }
}

可以添加什么样的断言来测试这个方法? 当然,您可以尝试捕获它,但这只是代码膨胀。

解决方案来自JUnit本身。

如果没有抛出异常,并且你想显式地说明这种行为,只需添加预期,如下例所示:

@Test(expected = Test.None.class /* no exception expected */)
public void test_printLine() {
    Printer.printLine("line");
}

Test.None.class是预期值的默认值。

如果您导入org.junit.Test。没有,你可以这样写:

@Test(expected = None.class)

你可能会觉得更有可读性。

这可能不是最好的方法,但它肯定能确保不会从正在测试的代码块抛出异常。

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
public ExpectedException expectedException = ExpectedException.none();