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") ;
}
}
}
To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.
JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.
In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.
@Test(expected = MyException.class)
public void testMethod2() throws MyException {
u.method2(9);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With