Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Exception testing with Junit 3

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?

like image 450
Mobidoy Avatar asked Nov 06 '12 13:11

Mobidoy


People also ask

How do you test exception handling in JUnit?

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.

Should JUnit tests throw exceptions?

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".

How do I create an expected exception in JUnit?

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.


1 Answers

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.

like image 175
Aaron Digulla Avatar answered Sep 16 '22 15:09

Aaron Digulla