Java:测试抛出已检查的异常

时间:2018-02-10 23:37:37

标签: java exception junit types

我试图想出一种方法来构建一个方法来测试是否确实抛出了已检查的异常。当我构建以下最小工作示例时(CustomThrowablexxx是为了便于阅读而在自己的文件上声明的所有自定义类型):

package demos.exceptions;

public class TestExceptions {

    // This method will check whether the provided method throws exceptions
    // of the type provided.
    private static boolean throwsParticularThrowable(Runnable method,
                                                 Class<Throwable> cls){
        try {
            method.run();
        } catch(Throwable t){
            if(t.getClass().equals(cls))
                return true;
        }
        return false;
    }

    private static void methodOne() throws CustomThrowableOne {
        throw new CustomThrowableOne("methodOne() throws");
    }

    private static void methodTwo() throws CustomThrowableTwo {
        throw new CustomThrowableTwo("methodTwo() throws");
    }

    private static void methodThree() throws CustomThrowableThree {
        throw new CustomThrowableThree("methodThree() throws");
     }

    public static void main(String[] args){

        if(!throwsParticularThrowable(TestExceptions::methodOne, 
                                             CustomThrowableOne.class))
            System.out.println("Nope!");
    }
}

我很遗憾地发现访问TestExceptions::methodOne并不安全,因为编译器抱怨我没有检查methodOne的投掷,我认为这是有道理的。

有没有什么方法可以让我自动化,而不是每次都在throwsParticularThrowable内复制和粘贴代码?

1 个答案:

答案 0 :(得分:2)

我不知道您在寻找什么,但如果使用JUnit ExpectedException抛出异常,则更容易测试

https://junit.org/junit4/javadoc/4.12/org/junit/rules/ExpectedException.html