Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jUnit same exception in different cases

I'm writing a jUnit test for a constructor that parses a String and then check numerous things. When there's wrong data, for every thing, some IllegalArgumentException with different message is thrown. So I would like to write tests for it, but how can i recognize what error was thrown? This is how can I do it:

@Test(expected=IllegalArgumentException.class)
public void testRodneCisloRok(){
    new RodneCislo("891415",dopocitej("891415"));
}

and this is how I would like to be, but I don't know if it is possible to write it somehow:

@Test(expected=IllegalArgumentException.class("error1"))
public void testRodneCisloRok(){
    new RodneCislo("891415",dopocitej("891415"));
}
like image 829
ryskajakub Avatar asked Mar 14 '10 22:03

ryskajakub


People also ask

Does JUnit support grouping of test cases?

JUnit test suites help to grouping and executing tests in bulk. Executing tests separately for all test classes is not desired in most cases. Test suites help in achieving this grouping. In JUnit, test suites can be created and executed with these annotations.

How would you assert an exception is thrown JUnit?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

How do I assert exception messages in junit4?

Test Exception in JUnit 4 @Rule public ExpectedException exception = ExpectedException. none(); Then in the test method you can use its expect() and expectMessage() to assert the type of expected exception and the exception message.


2 Answers

If you have JUnit 4.7 or above you can use this (elegant) way:

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}
like image 106
Filippo Vitale Avatar answered Oct 26 '22 15:10

Filippo Vitale


You'll need to do it the old fashioned way:

@Test
public void testRodneCisloRok() {
    try {
       new RodneCislo("891415",dopocitej("891415"));
       fail("expected an exception");
    } catch (IllegalArgumentException ex) {
       assertEquals("error1", ex.getMessage());
    }
}

The @Test(expected=...) syntax is a handy convenience, but it's too simple in many cases.

If it is important to distinguish between exception conditions, you might want to consider developing a class hierarchy of exceptions, that can be caught specifically. In this case, a subclass of IllegalArgumentException might be a good idea. It's arguably better design, and your test can catch that specific exception type.

like image 39
skaffman Avatar answered Oct 26 '22 17:10

skaffman