我知道有一种方法是:

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


当前回答

你可以基于junit的断言创建你自己的任何类型的断言,因为这些断言是专门为创建用户定义的断言而设计的,其工作方式与junit的断言完全一样:

static void assertDoesNotThrow(Executable executable) {
    assertDoesNotThrow(executable, "must not throw");
}
static void assertDoesNotThrow(Executable executable, String message) {
    try {
        executable.execute();
    } catch (Throwable err) {
        fail(message);
    }
}

现在测试所谓的场景methodMustNotThrow,并以junit风格记录所有失败:

//test and log with default and custom messages
//the following will succeed
assertDoesNotThrow(()->methodMustNotThrow(1));
assertDoesNotThrow(()->methodMustNotThrow(1), "custom facepalm");
//the following will fail
assertDoesNotThrow(()->methodMustNotThrow(2));
assertDoesNotThrow(()-> {throw new Exception("Hello world");}, "message");
//See implementation of methodMustNotThrow below

一般来说,在任何场景中,只要调用fail(someMessage)是有意义的,就有可能立即使测试中的任何内容失败,而fail(someMessage)正是为此目的而设计的。例如,在try/catch块中使用它,如果在测试用例中抛出任何东西,就会失败:

try{methodMustNotThrow(1);}catch(Throwable e){fail("must not throw");}
try{methodMustNotThrow(1);}catch(Throwable e){Assertions.fail("must not throw");}

这是我们测试的方法的样本,假设我们有这样一个方法,在特定的情况下一定不会失败,但它可以失败:

void methodMustNotThrow(int x) throws Exception {
    if (x == 1) return;
    throw new Exception();
}

上述方法是一个简单的示例。但这适用于复杂的情况,在这种情况下,失败不是那么明显。 这里有进口:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.*;

其他回答

Java 8让这变得容易多了,Kotlin/Scala更是如此。

我们可以写一个小工具类

class MyAssertions{
  public static void assertDoesNotThrow(FailingRunnable action){
    try{
      action.run()
    }
    catch(Exception ex){
      throw new Error("expected action not to throw, but it did!", ex)
    }
  }
}

@FunctionalInterface interface FailingRunnable { void run() throws Exception }

然后你的代码就变得很简单:

@Test
public void foo(){
  MyAssertions.assertDoesNotThrow(() -> {
    //execute code that you expect not to throw Exceptions.
  }
}

如果你不能使用java -8,我会使用一种非常古老的java工具:任意的代码块和一个简单的注释

//setup
Component component = new Component();

//act
configure(component);

//assert 
/*assert does not throw*/{
  component.doSomething();
}

最后,用kotlin,一种我最近爱上的语言:

fun (() -> Any?).shouldNotThrow() 
    = try { invoke() } catch (ex : Exception){ throw Error("expected not to throw!", ex) }

@Test fun `when foo happens should not throw`(){

  //...

  { /*code that shouldn't throw*/ }.shouldNotThrow()
}

尽管有很多空间可以随意改变你想要如何表达这一点,但我一直喜欢流畅的断言。


关于

你想错了。只需测试您的功能:如果抛出异常,测试将自动失败。如果没有抛出异常,您的测试将全部显示为绿色。

这在原则上是正确的,但在结论上是不正确的。

Java允许控制流的异常。这是由JRE运行时本身在Double等api中完成的。parseDouble通过NumberFormatException和路径。通过invalidpatheexception获取。

Given you've written a component that validates Number strings for Double.ParseDouble, maybe using a Regex, maybe a hand-written parser, or perhaps something that embeds some other domain rules that restricts the range of a double to something specific, how best to test this component? I think an obvious test would be to assert that, when the resulting string is parsed, no exception is thrown. I would write that test using either the above assertDoesNotThrow or /*comment*/{code} block. Something like

@Test public void given_validator_accepts_string_result_should_be_interpretable_by_doubleParseDouble(){
  //setup
  String input = "12.34E+26" //a string double with domain significance

  //act
  boolean isValid = component.validate(input)

  //assert -- using the library 'assertJ', my personal favourite 
  assertThat(isValid).describedAs(input + " was considered valid by component").isTrue();
  assertDoesNotThrow(() -> Double.parseDouble(input));
}

我还鼓励您使用Theories或Parameterized对输入参数化这个测试,这样您就可以更容易地对其他输入重复使用这个测试。或者,如果您想要与众不同,您可以使用测试生成工具(以及这个工具)。TestNG对参数化测试有更好的支持。

What I find particularly disagreeable is the recommendation of using @Test(expectedException=IllegalArgumentException.class), this exception is dangerously broad. If your code changes such that the component under test's constructor has if(constructorArgument <= 0) throw IllegalArgumentException(), and your test was supplying 0 for that argument because it was convenient --and this is very common, because good generating test data is a surprisingly hard problem--, then your test will be green-bar even though it tests nothing. Such a test is worse than useless.

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

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

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

}

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

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

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

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