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 di
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"));
}
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.