Java:使用Junit 3进行异常测试

Mob*_*doy 16 java error-handling junit exception junit3

我想写一个测试IndexOutOfBoundsException.请记住,我们应该使用JUnit 3.

我的代码:

public boolean ajouter(int indice, T element) {
    if (indice < 0 || indice > (maListe.size() - 1)) {
        throw new IndexOutOfBoundsException();
    } else if (element != null && !maListe.contains(element)) {
        maListe.set(indice, element);
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

经过一些研究,我发现你可以使用JUnit 4来实现这一点,@Test(expected = IndexOutOfBoundsException.class)但是我没有在JUnit 3中找到如何做到这一点.

如何使用JUnit 3进行测试?

Aar*_*lla 32

在JUnit 3中测试异常使用以下模式:

try {
     ... code that should throw an exception ...

     fail( "Missing exception" );
} catch( IndexOutOfBoundsException e ) {
     assertEquals( "Expected message", e.getMessage() ); // Optionally make sure you get the correct message, too
}
Run Code Online (Sandbox Code Playgroud)

fail()确保如果代码不抛出异常,你得到一个错误.

我在JUnit 4中也使用这种模式,因为我通常希望确保在异常消息中@Test可以看到正确的值而不能这样做.


Jon*_*eet 14

基本上,您需要调用您的方法,如果它没有抛出正确的异常,则会失败- 或者如果它抛出任何其他东西:

try {
  subject.ajouter(10, "foo");
  fail("Expected exception");
} catch (IndexOutOfBoundException expect) {
  // We should get here. You may assert things about the exception, if you want.
}
Run Code Online (Sandbox Code Playgroud)