-2
final GregorianCalendar calendar = new GregorianCalendar(); final XMLGregorianCalendar dt; try { dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); } catch (DatatypeConfigurationException e) { throw new IllegalArgumentException(e); } return dt; 
2
  • 1
    Does this answer your question? Try catch in a JUnit test Commented May 13, 2020 at 9:13
  • Please provide additional explanation what you want to achieve (not only a piece of code). Commented May 13, 2020 at 9:35

1 Answer 1

0

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(); }); } 
Sign up to request clarification or add additional context in comments.

5 Comments

does expected work for Junit5? as it would be amazing to use 5.
yes updated my ans with Junit5 test code @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:
@Test public void whenExceptionThrown_thenExpectationSatisfied() { Assertions.assertThrows(IllegalArgumentException.class, () -> { service.getDateAndTime(); }); }
your test method is expect an error but getCalendar will never throw an error so you have got the exception

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.