zl程序教程

您现在的位置是:首页 >  其它

当前栏目

mstest实现类似单元测试nunit中assert.throws功能

实现 功能 类似 单元测试 assert throws
2023-06-13 09:15:16 时间

我们做单元测试NUnit中,有一个断言Assert.Throws很好用,但当我们使用MsTest时你需要这样写:

复制代码代码如下:

[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
publicvoidWriteToTextFile()
{
PDFUtility.WriteToTextFile("D:\\ACA.pdf",null);
}

现在让我们来扩展一下也实现类似成功能,增加一个类,代码如下:

复制代码代码如下:

///<summary>
///Usefulassertionsforactionsthatareexpectedtothrowanexception.
///</summary>
publicstaticclassExceptionAssert
{
///<summary>
///Executesanexception,expectinganexceptiontobethrown.
///LikeAssert.ThrowsinNUnit.
///</summary>
///<paramname="action">Theactiontoexecute</param>
///<returns>Theexceptionthrownbytheaction</returns>
publicstaticExceptionThrows(Actionaction)
{
returnThrows(action,null);
}

///<summary>
///Executesanexception,expectinganexceptiontobethrown.
///LikeAssert.ThrowsinNUnit.
///</summary>
///<paramname="action">Theactiontoexecute</param>
///<paramname="message">Theerrormessageiftheexpectedexceptionisnotthrown</param>
///<returns>Theexceptionthrownbytheaction</returns>
publicstaticExceptionThrows(Actionaction,stringmessage)
{
try
{
action();
}
catch(Exceptionex)
{
//Theactionmethodhasthrowntheexpectedexception.
//Returntheexception,incasetheunittestwantstoperformfurtherassertionsonit.
returnex;
}

//Ifweenduphere,theexpectedexceptionwasnotthrown.Fail!
thrownewAssertFailedException(message??"Expectedexceptionwasnotthrown.");
}

///<summary>
///Executesanexception,expectinganexceptionofaspecifictypetobethrown.
///LikeAssert.ThrowsinNUnit.
///</summary>
///<paramname="action">Theactiontoexecute</param>
///<returns>Theexceptionthrownbytheaction</returns>
publicstaticTThrows<T>(Actionaction)whereT:Exception
{
returnThrows<T>(action,null);
}

///<summary>
///Executesanexception,expectinganexceptionofaspecifictypetobethrown.
///LikeAssert.ThrowsinNUnit.
///</summary>
///<paramname="action">Theactiontoexecute</param>
///<paramname="message">Theerrormessageiftheexpectedexceptionisnotthrown</param>
///<returns>Theexceptionthrownbytheaction</returns>
publicstaticTThrows<T>(Actionaction,stringmessage)whereT:Exception
{
try
{
action();
}
catch(Exceptionex)
{
Tactual=exasT;
if(actual==null)
{
thrownewAssertFailedException(message??String.Format("Expectedexceptionoftype{0}notthrown.Actualexceptiontypewas{1}.",typeof(T),ex.GetType()));
}

//Theactionmethodhasthrowntheexpectedexceptionoftype"T".
//Returntheexception,incasetheunittestwantstoperformfurtherassertionsonit.
returnactual;
}

//Ifweenduphere,theexpectedexceptionoftype"T"wasnotthrown.Fail!
thrownewAssertFailedException(message??String.Format("Expectedexceptionoftype{0}notthrown.",typeof(T)));
}
}

好了,现在我们在MsTest中可以这样了,看下面代码:
复制代码代码如下:
[TestMethod]
 publicvoidWriteToTextFile2()
{
//ImplementAssert.ThrowsinMSTest
ExceptionAssert.Throws<ArgumentNullException>(()=>PDFUtility.WriteToTextFile("D:\\ACA.pdf",null)
 ,"Outputfilepathshouldnotbenull");
 }