.jpg)
如何使用(或其他 Test 类)来验证在使用 MSTest/Microsoft.VisualStudio.TestTools.UnitTesting 时是否引发了异常?Assert

网友回答:
通常,您的测试框架会对此给出答案。但是,如果它不够灵活,您可以随时这样做:
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // If it gets to this line, no exception was thrown
} catch (GoodException) { }
正如@Jonas指出的那样,这不适用于捕获基本异常:
try {
somethingThatShouldThrowAnException();
Assert.Fail(); // raises AssertionException
} catch (Exception) {
// Catches the assertion exception, and the test passes
}
如果你绝对必须捕获异常,你需要重新抛出 Assert.Fail()。但实际上,这是一个迹象,你不应该手写这个;检查测试框架中的选项,或者查看是否可以引发更有意义的异常进行测试。
catch (AssertionException) { throw; }
您应该能够使此方法适应您喜欢的任何内容 – 包括指定要捕获的异常类型。如果您只期望某些类型,请使用以下命令完成块:catch
} catch (GoodException) {
} catch (Exception) {
// not the right kind of exception
Assert.Fail();
}

网友回答:
对于“Visual Studio Team Test”,您似乎将 ExpectException 属性应用于测试的方法。
此处文档中的示例:使用 Visual Studio 团队测试的单元测试演练
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}

网友回答:
我实现此目的的首选方法是编写一个名为 Throws 的方法,并像使用任何其他 Assert 方法一样使用它。遗憾的是,.NET 不允许你编写静态扩展方法,所以你不能使用此方法,就好像它实际上属于 Assert 类中的构建一样;只需制作另一个称为MyAssert或类似的东西。该类如下所示:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace YourProject.Tests
{
public static class MyAssert
{
public static void Throws<T>( Action func ) where T : Exception
{
var exceptionThrown = false;
try
{
func.Invoke();
}
catch ( T )
{
exceptionThrown = true;
}
if ( !exceptionThrown )
{
throw new AssertFailedException(
String.Format("An exception of type {0} was expected, but not thrown", typeof(T))
);
}
}
}
}
这意味着您的单元测试如下所示:
[TestMethod()]
public void ExceptionTest()
{
String testStr = null;
MyAssert.Throws<NullReferenceException>(() => testStr.ToUpper());
}
它的外观和行为更像单元测试语法的其余部分。
模板简介:该模板名称为【如何使用断言验证是否已使用 MSTest 引发异常?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。