我有一个类ServerConnection.java有以下方法
private String getUrl() throws MalformedURLException {
// some operations and condition
URL url = getDNSBasedUrl();
}
public String getDNSBasedUrl() throws MalformedURLException{
if(this.nameSpace==null)
throw new MalformedURLException("undefined namespace");
return this.nodeName + this.nameSpace;
}
测试用例如下所示
@Test(expected = MalformedURLException.class)
public void gctNameSpace_Exception(){
ServerConnection connection = new ServerConnection();
connection.setNameSpace(null);
String s = connection.getDNSBasedUrl();
}
我期待malformmedurlexception,但低于错误。
java.lang.Exception: Unexpected exception, expected<java.net.MalformedURLException> but was<java.lang.reflect.UndeclaredThrowableException>
不想改变从方法抛出的异常,getUrl()在很多地方被引用。提前谢谢。
当您的测试执行可以抛出MalformedURLException
的方法时,需要测试方法使用try-catch或try-finally来处理它,或者简单地声明要抛出的异常,如
@Test(expected = MalformedURLException.class)
public void gctNameSpace_Exception() throws MalformedURLException {
ServerConnection connection = new ServerConnection();
connection.setNameSpace();
String s = connection.getDNSBasedUrl();
}