我知道有一种方法是:

@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代码。

其他回答

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

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

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

以下是所有检查或未检查的异常都无法通过测试:

@Test
public void testMyCode() {

    try {
        runMyTestCode();
    } catch (Throwable t) {
        throw new Error("fail!");
    }
}

我最后是这样做的

@Test
fun `Should not throw`() {
    whenever(authService.isAdmin()).thenReturn(true)

    assertDoesNotThrow {
        service.throwIfNotAllowed("client")
    }
}

对于5之前的JUnit版本:

使用AssertJ fluent断言3.7.0:

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

更新:

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