【发布时间】:2013-12-18 15:42:39
【问题描述】:
我正在为我的类编写一个测试用例,其中包含抛出异常的方法(已检查和运行时)。正如link. 中所建议的那样,我尝试了不同的可能测试方法。看来它们似乎只适用于运行时异常。对于 Checked 异常,我需要执行 try/catch/assert,如下面的代码所示。是否有任何替代 try/catch/assert/.您会注意到 testmethod2() and testmethod2_1() 显示编译错误,但 testmethod2_2() 不显示使用 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);
}
}
测试类:
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") ;
}
}
}
【问题讨论】:
标签: java exception try-catch junit4 checked-exceptions