I would like to write a test for IndexOutOfBoundsException
. Keep in mind that we are supposed to use JUnit 3.
My code:
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;
}
}
After some research, I found that you can do this with JUnit 4 using @Test(expected = IndexOutOfBoundsException.class)
but no where did I find how to do this in JUnit 3.
How can I test this using JUnit 3?
Testing exceptions in JUnit 3 uses this pattern:
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
}
The fail()
makes sure you get an error if the code doesn't throw an exception.
I use this pattern in JUnit 4 as well since I usually want to make sure the correct values are visible in the exception message and @Test
can't do that.