简体   繁体   English

Java:测试抛出检查异常

[英]Java: testing for the throwing of checked exceptions

I'm trying to figure out a way to build a method that will test whether a checked exception has indeed been thrown. 我正在尝试找出一种方法来构建一种方法,该方法将测试是否确实抛出了一个已检查的异常。 As I was building the following minimal working example ( CustomThrowablexxx are all custom types declared on their own files for readability): 在构建下面的最小工作示例时( 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!");
    }
}

I unfortunately noticed that the access to TestExceptions::methodOne was not safe, because the compiler complained that I'm not checking for the throwing of methodOne , which I guess makes sense. 我不幸注意到,进入TestExceptions::methodOne并不安全,因为编译器抱怨我不检查的投掷methodOne ,我的猜测是有道理的。

Is there any way I can automate this instead of copying and pasting the code inside throwsParticularThrowable every time? 有什么方法可以throwsParticularThrowable自动化,而不是每次都将代码复制并粘贴到throwsParticularThrowable内部吗?

I don't know what you are looking for but it's easier to test if exceptions are thrown using JUnit ExpectedException 我不知道您在寻找什么,但是使用JUnit ExpectedException来测试是否抛出异常更容易

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM