@@ -0,0 +1,1583 @@
+package com.levelup.java.junit;%0A%0Aimport static org.hamcrest.CoreMatchers.isA;%0Aimport static org.junit.Assert.assertThat;%0Aimport static org.junit.Assert.fail;%0A%0Aimport java.util.ArrayList;%0Aimport java.util.List;%0A%0Aimport org.junit.Rule;%0Aimport org.junit.Test;%0Aimport org.junit.rules.ExpectedException;%0A%0A/**%0A * This java example will demonstrate testing for exception with junit.%0A * %0A * @author Justin Musgrove%0A * @see %3Ca href='http://www.leveluplunch.com/java/examples/junit-exception-testing/'%3EJunit exception testing%3C/a%3E%0A * %0A */%0Apublic class ExceptionTesting %7B%0A%0A%09@SuppressWarnings(%22null%22)%0A%09@Test(expected = NullPointerException.class)%0A%09public void check_for_nullpointer_exception_junit() %7B%0A%09%09%0A%09%09String test = null;%0A%09%09%0A%09%09if (test.length() == 5) %7B%7D%0A%09%7D%0A%0A%09@Test(expected = IndexOutOfBoundsException.class)%0A%09public void check_for_indexoutofbounds_exception_junit() %7B%0A%09%09new ArrayList%3CString%3E().get(0);%0A%09%7D%0A%0A%09@Test%0A%09public void test_for_exception_try_catch_junit() %7B%0A%09%09try %7B%0A%09%09%09new ArrayList%3CString%3E().get(0);%0A%09%09%09fail(%22Expected an IndexOutOfBoundsException to be thrown%22);%0A%09%09%09%0A%09%09%7D catch (IndexOutOfBoundsException e) %7B%0A%09%09%09assertThat(%0A%09%09%09%09%09e.getMessage(),%0A%09%09%09%09%09isA(String.class));%0A%09%09%7D%0A%09%7D%0A%09  %0A%09@Rule public ExpectedException thrown = ExpectedException.none();%0A%0A    @Test%0A    public void test_for_exception_with_rule_junit() throws IndexOutOfBoundsException %7B%0A        List%3CString%3E list = new ArrayList%3CString%3E();%0A%0A        thrown.expect(IndexOutOfBoundsException.class);%0A        thrown.expectMessage(%22Index: 0, Size: 0%22);%0A        list.get(0); // execution will never get past this line%0A    %7D%0A%09%0A%7D%0A

add exception testing