我知道有一种方法是:

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


当前回答

如果您不幸捕获了代码中的所有错误。 你可以愚蠢地做

class DumpTest {
    Exception ex;
    @Test
    public void testWhatEver() {
        try {
            thisShouldThrowError();
        } catch (Exception e) {
            ex = e;
        }
        assertEquals(null,ex);
    }
}

其他回答

在这个问题上遇到了麻烦,因为我创建了一些泛型方法

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

使用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();
});

JUnit5为此添加了assertAll()方法。

assertAll( () -> foo() )

来源:JUnit 5 API

对于5之前的JUnit版本:

使用AssertJ fluent断言3.7.0:

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

更新:

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