我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
MSTest (v2)现在有一个Assert。ThrowsException函数,可以像这样使用:
Assert.ThrowsException<System.FormatException>(() =>
{
Story actual = PersonalSite.Services.Content.ExtractHeader(String.Empty);
});
您可以使用nuget: install - package MSTest安装它。TestFramework
其他回答
如果你使用NUNIT,你可以这样做:
Assert.Throws<ExpectedException>(() => methodToTest());
也可以存储抛出的异常以便进一步验证:
ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest());
Assert.AreEqual( "Expected message text.", ex.Message );
Assert.AreEqual( 5, ex.SomeNumber);
参见:http://nunit.org/docs/2.5/exceptionAsserts.html
在使用NUnit的情况下,试试这个:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
查看nUnit文档中的例子:
[ExpectedException( typeof( ArgumentException ) )]
对于“Visual Studio Team Test”,似乎您将ExpectedException属性应用到测试的方法。
文档中的示例:使用Visual Studio团队测试的单元测试演练
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
你可以从Nuget下载一个包,使用:PM> Install-Package MSTestExtensions将Assert.Throws()语法以nUnit/xUnit的风格添加到MsTest。
高级指令:从BaseTest下载程序集并继承,您可以使用Assert.Throws()语法。
Throws实现的主要方法如下所示:
public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
try
{
task();
}
catch (Exception ex)
{
AssertExceptionType<T>(ex);
AssertExceptionMessage(ex, expectedMessage, options);
return;
}
if (typeof(T).Equals(new Exception().GetType()))
{
Assert.Fail("Expected exception but no exception was thrown.");
}
else
{
Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
}
}
披露:我整理了这个包。
更多信息:http://www.bradoncode.com/blog/2012/01/asserting-exceptions-in-mstest-with.html
推荐文章
- 我如何使一个方法的返回类型泛型?
- 在PHP单元测试执行期间,如何在CLI中输出?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 单元测试的一些常用命名约定是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空