是否有一些Assert方法可用于关于方法是否引发异常的单元测试? [英] Is there some Assert method which can be used for unit test on whether a method throws an exception?

查看:141
本文介绍了是否有一些Assert方法可用于关于方法是否引发异常的单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我有一个方法,当某个条件为true时会引发异常.我应该写一个单元测试方法来验证这一点.

In C#, I have a method which throws an exception when a certain condition is true. I am supposed to write a unit test method to verify that.

由于要测试的方法不返回布尔值,所以我不能使用Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue方法.我可以使用哪种断言方法?谢谢.

Since the method being tested doesn't return a boolean value, I can't use Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue method. Which assert method can I use? Thanks.

推荐答案

使用Assert.Throws,如下所示:

var ex = Assert.Throws<ArgumentNullException>(() => My.Method(null));
Assert.Equals("foo", ex.ParamName);

这可以在XUnit和更高版本的MSTest中使用(以 NuGet软件包的形式安装MSTest 获取最新版本)

This works in XUnit and in the later versions of MSTest (install MSTest as a NuGet package to get up-to-date versions)

这篇关于是否有一些Assert方法可用于关于方法是否引发异常的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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