Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:抛出已检查异常的测试_Java_Exception_Junit_Types - Fatal编程技术网

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

Java:抛出已检查异常的测试,java,exception,junit,types,Java,Exception,Junit,Types,我试图找出一种方法来构建一个方法,该方法将测试是否确实抛出了一个已检查的异常。在我构建以下最小工作示例时(CustomThrowablexxx都是为可读性在自己的文件中声明的自定义类型): package demos.exceptions; 公共类测试异常{ //此方法将检查提供的方法是否引发异常 //提供的类型。 私有静态布尔ThrowSpecialThrowTable(Runnable方法, 类别(cls){ 试一试{ 方法run(); }捕获(可丢弃的t){ 如果(t.getClass()

我试图找出一种方法来构建一个方法,该方法将测试是否确实抛出了一个已检查的异常。在我构建以下最小工作示例时(
CustomThrowablexxx
都是为可读性在自己的文件中声明的自定义类型):

package demos.exceptions;
公共类测试异常{
//此方法将检查提供的方法是否引发异常
//提供的类型。
私有静态布尔ThrowSpecialThrowTable(Runnable方法,
类别(cls){
试一试{
方法run();
}捕获(可丢弃的t){
如果(t.getClass()等于(cls))
返回true;
}
返回false;
}
私有静态void methodOne()抛出CustomThrowableOne{
抛出新的CustomThrowableOne(“methodOne()抛出”);
}
私有静态void methodTwo()抛出CustomThrowableTwo{
抛出新的CustomThrowableTwo(“methodTwo()抛出”);
}
私有静态void methodThree()抛出CustomThrowableTree{
抛出新的CustomThrowableThree(“methodThree()抛出”);
}
公共静态void main(字符串[]args){
如果(!ThrowSpecialThrowable(TestExceptions::methodOne,
CustomThrowableOne.class)
System.out.println(“不!”);
}
}
不幸的是,我注意到对
TestExceptions::methodOne
的访问不安全,因为编译器抱怨我没有检查抛出
methodOne
,我想这是有道理的


有没有什么方法可以让我自动执行此操作,而不是每次都通过特定的RowTable来复制和粘贴
中的代码?

我不知道您在寻找什么,但是使用JUnit ExpectedException测试是否引发异常会更容易


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

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!");
    }
}