如何使用Assert验证是否已引发异常?

如何使用Assert(或其他Test类?)来验证是否已引发异常?



回首忆惘然
浏览 2411回答 3
3回答

桃花长相依

对于“ Visual Studio Team Test”,您似乎将ExpectedException属性应用于该测试的方法。这里的文档样本:使用Visual Studio Team Test进行单元测试的演练[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{&nbsp; &nbsp; public static class MyAssert&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public static void Throws<T>( Action func ) where T : Exception&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var exceptionThrown = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; func.Invoke();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; catch ( T )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exceptionThrown = true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ( !exceptionThrown )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new AssertFailedException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String.Format("An exception of type {0} was expected, but not thrown", typeof(T))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这意味着您的单元测试如下所示:[TestMethod()]public void ExceptionTest(){&nbsp; &nbsp; String testStr = null;&nbsp; &nbsp; MyAssert.Throws<NullReferenceException>(() => testStr.ToUpper());}它的外观和行为更像其余的单元测试语法。
打开App,查看更多内容
随时随地看视频慕课网APP