【问题标题】:Junit-Expected MalformedURLException but got UndeclaredThrowableExceptionJunit-Expected MalformedURLException 但得到了 UndeclaredThrowableException
【发布时间】:2023-01-10 03:15:51
【问题描述】:

我有一个 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();
}

我期待 MalformedURLException 但低于错误。

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

不想更改方法抛出的异常,getUrl() 在许多地方被引用。 提前致谢。

【问题讨论】:

    标签: java exception junit mockito malformedurlexception


    【解决方案1】:

    当您的测试执行一个可以抛出 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();
    }
    

    【讨论】:

    • 尝试了上述解决方案,没有用。我也在其他方法中处理异常,这就是我使用 throws 关键字的原因。
    猜你喜欢
    • 2022-12-11
    • 2022-11-17
    • 2011-08-31
    • 2022-01-21
    • 2021-06-25
    • 2017-12-29
    • 2021-03-11
    • 2022-01-20
    • 2021-11-30
    相关资源
    最近更新 更多