assertThrows()表现良好,但它应该失败
创始人
2024-09-20 16:30:16
0

assertThrows()是JUnit 5中的一个断言方法,用于测试抛出异常的情况。例如,可以使用assertThrows()来测试方法是否会抛出NullPointerException或IllegalArgumentException等异常。

在某些情况下,assertThrows()可能会无法捕获异常,导致测试失败。这通常是由于测试方法本身已经捕获了异常,或者异常类型不正确。为了测试这种情况,我们可以手动添加一个失败条件来检测是否没有抛出预期的异常。

以下是示例代码,演示如何添加失败条件来测试assertThrows()是否起作用:

@Test void testDivideByZero_shouldThrowException() { Calculator calculator = new Calculator(); assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0), "Expected ArithmeticException to be thrown"); assertThrowsFail(); }

private void assertThrowsFail() { try { assertThrows(Exception.class, () -> {}); fail("assertThrows() failed to throw Exception"); } catch (AssertionError e) { // expected } }

上述代码首先使用assertThrows()测试divide()方法是否会抛出ArithmeticException。然后,它使用assertThrowsFail()方法来测试assertThrows()本身是否会抛出Exception。由于没有任何代码在lambda表达式中执行,这意味着assertThrows()应该会抛出一个异常。如果assertThrows()不抛出异常,fail()方法就会抛出一个AssertionError以产生失败条件。

通过这种方法,我们可以确保assertThrows()方法的可靠性,保证在测试中正确捕获异常。

相关内容

热门资讯

透视美元局!aa poker透... 透视美元局!aa poker透视软件(透视)aapoker插件下载,解密教程(有挂插件)1、玩家可以...
透视辅助!wepoker辅助真... 透视辅助!wepoker辅助真的假的,wepoker辅助软件价格(详细辅助软件)1、全新机制【wep...
透视脚本!aapoker公共底... 透视脚本!aapoker公共底牌(透视)aapoker怎么选牌,揭秘攻略(有挂技巧)1、完成aapo...
辅助透视!wepoker透视脚... 辅助透视!wepoker透视脚本下载,wejoker开挂(详细免费钻石)1、玩家可以在wepoker...
透视有挂!aapoker透视插... 透视有挂!aapoker透视插件(透视)aapoker辅助怎么用,存在挂教程(有挂解密);1、完成a...
透视私人局!wepoker数据... 透视私人局!wepoker数据分析,wepoker有没有插件(详细有辅助器)1、点击下载安装,wep...
透视美元局!aa poker透... 透视美元局!aa poker透视软件(透视)aapoker插件下载,解密教程(有挂解说)1)aa p...
透视app!wepoker透视... 透视app!wepoker透视脚本免费使用视频,wepoker透视有没有(详细辅助器下载);1、让任...
透视美元局!aapoker怎么... 透视美元局!aapoker怎么控制牌(透视)aapoker透视怎么用,AI教程(有挂解说)1、操作简...
透视计算!wepoker代打辅... 透视计算!wepoker代打辅助机器人,wepoker辅助器怎么弄(详细辅助器)亲,关键说明,wep...