我知道有一种方法是:

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


当前回答

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

assertAll( () -> foo() )

来源:JUnit 5 API

其他回答

使用assertNull(…)

@Test
public void foo() {
    try {
        //execute code that you expect not to throw Exceptions.
    } catch (Exception e){
        assertNull(e);
    }
}

我遇到了同样的情况,我需要检查异常是否在应该抛出的时候抛出,并且仅在应该抛出的时候抛出。 最终使用异常处理程序对我的好处如下代码:

    try {
        functionThatMightThrowException()
    }catch (Exception e){
        Assert.fail("should not throw exception");
    }
    RestOfAssertions();

对我来说,主要的好处是它非常直截了当,并且在相同的结构中检查“如果且仅当”的另一种方式非常容易

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

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

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

我偶然发现这一点是因为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)

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