测试异常时的单元测试最佳实践

编程入门 行业动态 更新时间:2024-10-25 02:21:54
本文介绍了测试异常时的单元测试最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我一直在对android应用程序进行单元测试,尽管在某些情况下我会测试失败的情况,但我并没有按照此答案所建议的方式对其进行测试(尝试在JUnit测试中捕获).

So I've been unit testing an android application, and while there are cases that I test with fail scenarios, I don't test them quite the way this answer is suggesting (Try catch in a JUnit test).

我以下面的代码显示的方式对其进行了测试.答案是建议您在测试方法签名上具有引发异常",因为如果它实际上引发了您不希望的异常,它将使测试失败.但是,我尝试使用和不使用这段代码,它都以相同的方式失败. 上面提供的答案也使用规则"来进行这种测试,因为我需要的所有东西都将它们放在try catch块中,并且实例化是在@Before方法中完成的,因此我没有使用过.

I test it the way it shows on the code below. The answer is suggesting that you should have on test method signature the "throws Exception", since if it actually throws an exception you don't expect, it will fail the test. However i tried it with and without that piece of code, and it fails the same way. The answer provided above, also approaches this kind of test with the use of "rule", which i haven't used, since everything i need i have them inside my try catch block, and the instantiations are done inside a @Before method.

@Test public void testMethod() { try{ //code that will throw exception fail("Exception was not thrown"); } catch (/* types of exceptions */) { //my asserts } }

我追求的是哪种方法被认为是最佳实践"及其背后的原因.

What I'm after is which approach is considered "best practice" and the reason behind it.

推荐答案

@Test批注的expected属性用于定义测试用例,以检查是否引发了特定的异常.另外,还有@Rules注释,用于更具体的控制和不建议使用的"try-catch"习惯用法.有关示例,请参见此和 junit Wiki .

There's the expected attribute of the @Test annotation to define test cases that check if specific exceptions get raised. Alternatively there's the @Rules annotation for more specific control and a somewhat deprecated "try-catch" idiom. For samples see this and the junit wiki.

@Test(expected = IllegalArgumentException.class)

更多推荐

测试异常时的单元测试最佳实践

本文发布于:2023-10-31 05:05:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545087.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   异常   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!