writing a JUnit Test case for custom checked exception in Java?
checked-exceptions, exception, java, junit4, try-catch
Solution
@Test(expected = MyException.class)
public void testMethod2() throws MyException {
u.method2(9);
}
Problem
I am writing a test case for my class that has methods which throw exceptions (both checked and runtime). I have tried different possible ways of testing as suggested in this link.. It appears they seem to work only for runtime exceptions. for Checked exceptions, I need to do a try/catch/assert as shown in the code below. Is there any alternatives to try/catch/assert/. you will notice that `testmethod2() and testmethod2_1()` shows compile error but `testmethod2_2()` does not show compile error which uses try/catch. ``` class MyException extends Exception { public MyException(String message){ super(message); } } public class UsualStuff { public void method1(int i) throws IllegalArgumentException{ if (i<0) throw new IllegalArgumentException("value cannot be negative"); System.out.println("The positive value is " + i ); } public void method2(int i) throws MyException { if (i<10) throw new MyException("value is less than 10"); System.out.println("The value is "+ i); } } ``` Test class: ``` import static org.junit.Assert.*; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class UsualStuffTest { private UsualStuff u; @Before public void setUp() throws Exception { u = new UsualStuff(); } @Rule public ExpectedException exception = ExpectedException.none(); @Test(expected = IllegalArgumentException.class) public void testMethod1() { u.method1(-1); } @Test(expected = MyException.class) public void testMethod2() { u.method2(9); } @Test public void testMethod2_1(){ exception.expect(MyException.class); u.method2(3); } public void testMethod2_3(){ try { u.method2(5); } catch (MyException e) { assertEquals(e.getMessage(), "value is less than 10") ; } } } ```