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?
Create a java class file named TestRunner. java in C:\>JUNIT_WORKSPACE to execute test case(s). Compile the MessageUtil, Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test cases defined in the provided Test Case class.
The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer. I'll add that I think the question here is one of style: catch-and-fail, or throw? Normally, best practice avoids "throws Exception".
Example@Test(expected=IllegalArgumentException.class) By using “expected” parameter, you can specify the exception name our test may throw. In above example, you are using “IllegalArgumentException” which will be thrown by the test if a developer uses an argument which is not permitted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With