final GregorianCalendar calendar = new GregorianCalendar();
final XMLGregorianCalendar dt;
try {
dt = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
} catch (DatatypeConfigurationException e) {
throw new IllegalArgumentException(e);
} return dt;
Asked
Active
Viewed 565 times
-2
-
1Does this answer your question? [Try catch in a JUnit test](https://stackoverflow.com/questions/31423643/try-catch-in-a-junit-test) – Smile May 13 '20 at 09:13
-
Please provide additional explanation what you want to achieve (not only a piece of code). – SternK May 13 '20 at 09:35
1 Answers
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();
});
}

QuickSilver
- 3,915
- 2
- 13
- 29
-
-
-
Read this doc (https://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 May 13 '20 at 10:26
-
@Test public void whenExceptionThrown_thenExpectationSatisfied() { Assertions.assertThrows(IllegalArgumentException.class, () -> { service.getDateAndTime(); }); } – MoonMaker May 13 '20 at 10:26
-
your test method is expect an error but getCalendar will never throw an error so you have got the exception – QuickSilver May 13 '20 at 10:40