在Java中为自定义检查异常编写JUnit测试用例?

bra*_*orm 5 java exception try-catch junit4 checked-exceptions

我正在为我的类编写一个测试用例,其中包含抛出异常的方法(包括checked和runtime).我已尝试过此链接中建议的不同可能的测试方法..看起来它们似乎只适用于运行时异常.对于Checked异常,我需要执行try/catch/assert,如下面的代码所示.有没有替代尝试/ catch /断言/.你会注意到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);
    }

    }
Run Code Online (Sandbox Code Playgroud)

测试类:

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") ;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

jta*_*orn 18

@Test(expected = MyException.class)
public void testMethod2() throws MyException {
    u.method2(9);
}
Run Code Online (Sandbox Code Playgroud)

  • @ user1988876 - 因为java编译器对junit注释及其含义一无所知. (5认同)
  • 为什么我应该抛出`MyException`而我有@test(expected = MyException.class)`装饰器. (2认同)