final GregorianCalendar calendar = new GregorianCalendar(); final XMLGregorianCalendar dt; try { dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { throw new IllegalArgumentException(e); } return dt; - 1Does this answer your question? Try catch in a JUnit testSmile– Smile2020-05-13 09:13:00 +00:00Commented May 13, 2020 at 9:13
- Please provide additional explanation what you want to achieve (not only a piece of code).SternK– SternK2020-05-13 09:35:47 +00:00Commented May 13, 2020 at 9:35
Add a comment |
1 Answer
You can write a Junit4 libraries to test the IllegalArgumentException.class exception as below assuming your method signature is XMLGregorianCalendar getCalendar()
@Test(expected = IllegalArgumentException.class) public void whenExceptionThrown_thenExpectationSatisfied() { getCalendar(); } XMLGregorianCalendar getCalendar() { final GregorianCalendar calendar = new GregorianCalendar(); final XMLGregorianCalendar dt; try { dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { throw new IllegalArgumentException(e); } return dt; } For Junit 5
@Test void testGetCalendar() { Assertions.assertThrows(IllegalArgumentException.class, () -> { getCalendar(); }); } 5 Comments
MoonMaker
does expected work for Junit5? as it would be amazing to use 5.
QuickSilver
yes updated my ans with Junit5 test code @MoonMaker
MoonMaker
Read this doc (howtodoinjava.com/junit5/expected-exception-example) and got the same answer , but is complaining about org.opentest4j.AssertionFailedError: Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown:
MoonMaker
@Test public void whenExceptionThrown_thenExpectationSatisfied() { Assertions.assertThrows(IllegalArgumentException.class, () -> { service.getDateAndTime(); }); }
QuickSilver
your test method is expect an error but getCalendar will never throw an error so you have got the exception