JUnit测试自定义异常

Has*_*ash 7 java junit unit-testing exception junit4

我正在使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

主要类会有很多尝试捕获,如;

catch (ParseException e) {

    throw new CustomException("Date format incorerect", e);
Run Code Online (Sandbox Code Playgroud)

而且我不确定如何为它编写测试类..非常感谢.

谢谢.

Vid*_*dya 14

页面应该告诉您需要知道的一切.对于最简单的情况,这似乎是你的情况,只需这样做:

@Test(expected= CustomException.class) 
public void myTest() { 
  MyObject obj = new MyObject();
  obj.doSomethingThatMightThrowCustomException(); 
} 
Run Code Online (Sandbox Code Playgroud)