6

我正在为我的类编写一个测试用例,其中包含抛出异常的方法(已检查和运行时)。我已经尝试过此链接中建议的不同可能的测试方式。. 看来它们似乎只适用于运行时异常。对于 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") ;
        }
    }
}
4

1 回答 1

19
@Test(expected = MyException.class)
public void testMethod2() throws MyException {
    u.method2(9);
}
于 2013-12-02T20:19:36.593 回答