Junit-Expected MalformedURLException but got UndeclaredThrowableException

200 views Asked by At

I have a class ServerConnection.java which have below methods

 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 case is written as below

@Test(expected = MalformedURLException.class)
public void gctNameSpace_Exception(){
 ServerConnection connection = new ServerConnection();
 connection.setNameSpace(null);
 String s = connection.getDNSBasedUrl();
}

I am expecting MalformedURLException but getting below error.

java.lang.Exception: Unexpected exception, expected<java.net.MalformedURLException> but was<java.lang.reflect.UndeclaredThrowableException>

Don't want to change exceptions thrown from methods, getUrl() is referenced at many places. Thanks in advance.

1

There are 1 answers

4
cyberbrain On

As your test executes a method that can throw a MalformedURLException it is required that the test method either handles it with a try-catch or try-finally or simply declares that exception to be thrown, like

@Test(expected = MalformedURLException.class)
public void gctNameSpace_Exception() throws MalformedURLException {
  ServerConnection connection = new ServerConnection();
  connection.setNameSpace();
  String s = connection.getDNSBasedUrl();
}