Java JUnit 测试自定义异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19533210/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:05:32  来源:igfitidea点击:

JUnit testing custom exception

javaunit-testingexceptionjunitjunit4

提问by Hash

I'm using JUnit and not quite sure how to test custom exception class. I have created,

我正在使用 JUnit 并且不太确定如何测试自定义异常类。我创造了,

public class CustomException extends Exception {

    //@param message is the exception message

    public CustomException(final String message) {
        super(message);
    }

    //@param message is the exception message
    //@param cause is the cause of the original exception

    public CustomException(final String message, final Throwable cause) {
        super(message, cause);
    }
}

main class would have many try catch such as:

主类会有很多尝试捕获,例如:

catch (ParseException e) {

    throw new CustomException("Date format incorerect", e);

and I'm not sure how to write the test class for it.

我不确定如何为它编写测试类。

采纳答案by Vidya

This pageshould tell you everything you need to know. For the simplest case, which seems to be your case, just do this:

这个页面应该告诉你你需要知道的一切。对于最简单的情况,这似乎是您的情况,只需执行以下操作:

@Test(expected= CustomException.class) 
public void myTest() { 
  MyObject obj = new MyObject();
  obj.doSomethingThatMightThrowCustomException(); 
} 

回答by Ashok kumar

I hope this can help you.

我希望这可以帮助你。

public class YourTestClass
{
    @Test
    public void yourTestMethodName() throws CustomeException {
        //your logic goes here.
        if (condition) {
           throw new CustomeException(<Message to display while throwing an error>);
        }
    }
}

Also you can try the following site http://junit.sourceforge.net/javadoc/org/junit/Test.html

您也可以尝试以下站点http://junit.sourceforge.net/javadoc/org/junit/Test.html