【问题标题】:How to test for the exception in junit [duplicate]如何在junit中测试异常[重复]
【发布时间】:2018-07-20 11:22:09
【问题描述】:

假设我的方法 myMethod 检查了一系列场景,然后相应地抛出异常而不处理这些异常。

public MyResponse myMethod(MyRequest req)
{
    try
       {
          if(req.property1 == null || req.property1.isEmpty())
             throw new Exception("Property 1 is null of empty");

          if(req.property2 == null || req.property2.isEmpty())
             throw new Exception("Property 2 is null of empty");

          //if no problem is found then proceed ...
       }
       catch(Exception e)
       {
          //log error
          throw e;
       }

}

如何测试引发的异常或至少检查与异常一起发送的消息?

@Test
public void aNullOrEmptyProperty1CausesExceptionTest() throws Exception {
    //..
    String property1 = "";
    req.setProperty1(property1);
    //...
    MyResponse response = target.myMethod(req);

    //How to check for the exception?
}

感谢您的帮助

【问题讨论】:

  • 就像你在 myMethod 中所做的一样,你会想要 catch 它。
  • 我需要赶上吗?

标签: java junit


【解决方案1】:

我不知道它是否适用于所有版本的 JUnit(我使用的是 junit 4.12)。我通常做的是在Test注解之后添加预期的异常,例如:

@Test(expected = MySpecificException.class)

还有其他方法可以做,但这是可能的。您可以创建一个特定的 MySpecificException 类(它扩展了 Exception 类),然后在代码中抛出这个特定的异常。然后你可以用junit检查它是否正确抛出。

玩得开心!

【讨论】:

  • 查看链接的重复答案,了解为什么这并不总是有效。
  • 它工作正常。如果您想访问异常对象并读取发送的消息怎么办?
猜你喜欢
  • 2016-12-07
  • 2013-02-19
  • 1970-01-01
  • 2013-11-01
  • 2011-05-28
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多