-
try - catch
@Test public void testInvalidData() { prepareTestData(); try { userService.fetchUser(1234); Assert.fail("IllegalArgumentException not thrown"); } catch (IllegalArgumentException expected) { } }
-
Annotation Attribute
@Test(expected = IllegalArgumentException.class) public void testInvalidData() { prepareTestData(); // should throw IllegalArgumentException userService.fetchUser(1234); }
Junit5 以后不再有这个feature
-
Rule ExpectedException
@Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testInvalidData() { prepareTestData(); thrown.expect(IllegalArgumentException.class); userService.fetchUser(1234); }
JUnit 4 contains the built-in rule ExpectedException. (please remember that JUnit 5 uses extensions instead of rules).
This approach is similar to try-catch and
@Test(expected = ...)
, but we can control from which point the exception is expected. -
assertThrows
@Test public void testInvalidData() { prepareTestData(); Assertions.assertThrows(IllegalArgumentException.class, () -> { userService.fetchUser(1234); }); }
Assertions.assertThrows
also returns the exception object to execute further asserts, e.g. to assert the message.
Summary
I try to use assertThrows
as often as possible because the test code gets both readable and flexible. But all the other mentioned approaches are also valid if correctly used.