The basic idea is to surround the method you want to test with a try catch block and pass it an argument that will trigger the IllegalArgumentException to be thrown. The fail method call should never be reached, and if it does the unit test should fail. What should happen is that the IllegalArgumentException is caught, followed by a check for the correct message.
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.fail; import org.junit.Test; /** * The following example code demonstrates how to unit test Exceptions with JUnit and Hamcrest */ public class ExceptionUnitTesting { @Test public void test() { try { blah("asdf"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is(equalTo("Argument foo is not valid!"))); } } /** * @param foo * @throws IllegalArgumentException - in this test case always */ private void blah(String foo) { throw new IllegalArgumentException("Argument foo is not valid!"); } }
Piece of Cake!!!