2013-10-23 103 views
3

我正在使用JUnit,不太清楚如何测试自定义异常类。我创建了,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); 

    } 
} 

主类会有很多try catch如:

catch (ParseException e) { 

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

我不知道如何编写测试类的..任何帮助表示赞赏。

谢谢。

+0

要知道如何测试你需要什么东西你应该做什么的规范。你还没有提供这样的规范,所以这个问题是不可能回答的。 – Raedwald

回答

10

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

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

我希望这可以帮助你。你

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

也可以尝试下面的网站http://junit.sourceforge.net/javadoc/org/junit/Test.html