How can I use JUnit4 idiomatically to test that some code throws an exception?
While I can certainly do something like this:
@Test
public void testFo
In JUnit 4 or later you can test the exceptions as follows
@Rule
public ExpectedException exceptions = ExpectedException.none();
this provides a lot of features which can be used to improve our JUnit tests.
If you see the below example I am testing 3 things on the exception.
public class MyTest {
@Rule
public ExpectedException exceptions = ExpectedException.none();
ClassUnderTest classUnderTest;
@Before
public void setUp() throws Exception {
classUnderTest = new ClassUnderTest();
}
@Test
public void testAppleisSweetAndRed() throws Exception {
exceptions.expect(Exception.class);
exceptions.expectMessage("this is the exception message");
exceptions.expectCause(Matchers.equalTo(exceptionCause));
classUnderTest.methodUnderTest("param1", "param2");
}
}