使用JUnit进行单元测试时如何处理异常? [英] How to handle exceptions while unit testing using JUnit?

查看:569
本文介绍了使用JUnit进行单元测试时如何处理异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个抛出异常的方法,如何编写一个测试用例来验证该方法是否正在抛出预期的异常?

If a method throwing an exception, how to write a test case to verify that method is actually throwing the expected exception?

推荐答案

p>您可以尝试并捕获所需的异常,并执行类似 assertTrue(true)

You can try and catch the desired exception and do something like assertTrue(true):

@Test
testIfThrowsException(){
    try{
        funcThatShouldThrowException(arg1, agr2, agr3);
        assertTrue("Exception wasn't thrown", false);
    }
    catch(DesiredException de){
        assertTrue(true);
    }
}

这篇关于使用JUnit进行单元测试时如何处理异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆