JUnit same exception in different cases

I am writing a jUnit test for a constructor that parses a string and then checks a lot of things. When there is incorrect data, for each thing some IllegalArgumentException is thrown with another message. So I would like to write tests for it, but how can I find out which error was selected? Here's how I can do it:

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

and that’s exactly how I would like to be, but I don’t know if it can be written somehow:

 @Test(expected=IllegalArgumentException.class("error1")) public void testRodneCisloRok(){ new RodneCislo("891415",dopocitej("891415")); } 
+10
java unit-testing junit
Mar 14 '10 at 22:29
source share
2 answers

You will need to do this 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 syntax @Test(expected=...) convenient, but in many cases it is too simple.

If it is important to distinguish between exception conditions, you might consider creating a hierarchy of exception classes that can be caught on purpose. In this case, subclassing IllegalArgumentException might be a good idea. This is arguably the best design, and your test may catch this particular type of exception.

+4
Mar 14 '10 at 22:31
source share

If you have JUnit 4.7 or higher, 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")); } 
+32
Apr 17 '11 at 12:35
source share



All Articles