在单元测试中引发异常时,如何获得100%的覆盖率?

编程入门 行业动态 更新时间:2024-10-25 08:16:07
本文介绍了在单元测试中引发异常时,如何获得100%的覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在 C#中,您可以在默认测试套件中捕获如下异常:

In C# you can catch an exception in the default test suite like this:

[TestMethod] [ExpectedException(typeof (ArgumentNullException))] public void TestNullComposite() { IApi api = new Api(); api.GetDataUsingDataContract(null); // this method throws ArgumentNullException }

但是,当您分析代码覆盖率时,它说您只得到66.67%的覆盖率,因为最后一个花括号没有被覆盖.

But when you analyze the code coverage, it says that you only get 66.67% coverage because the last curly brace was not covered.

在该单元测试中,我将如何实现100%的覆盖率?

How would I go about achieving 100% coverage on this unit test?

推荐答案

在 NUnit 您有方法 Assert.Throws< Exception>() ,它检查是否抛出了所需的异常.它还会将该异常作为返回值返回,以便您可以根据需要进一步声明:

Within NUnit you have a method Assert.Throws<Exception>(), which checks if the desired exception was thrown. It also returns that exception as return value, so that you could have further assertations if you like:

[Test] public void Api_GetDataUsingDataContractWithNullParameter_ThrowsArgumentNullException() { var api = new Api(); var exception = Assert.Throws<ArgumentNullException>(() => api.GetDataUsingDataContract(null)); Assert.That(exception.Message, Is.Not.Null.Or.Empty); Assert.That(exception.Message, Is.StringContaining("source")); }

由于该方法不会自行抛出,因此您的覆盖率将为100%.

Due to the fact, that the method does not throw by itself, your coverage would be 100%.

更多推荐

在单元测试中引发异常时,如何获得100%的覆盖率?

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

发布评论

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

>www.elefans.com

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