3 回答

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
對(duì)于“ Visual Studio Team Test”,您似乎將ExpectedException屬性應(yīng)用于該測試的方法。
這里的文檔樣本:使用Visual Studio Team Test進(jìn)行單元測試的演練
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
實(shí)現(xiàn)此目的的首選方法是編寫一個(gè)稱為Throws的方法,并像其他任何Assert方法一樣使用它。不幸的是,.NET不允許您編寫靜態(tài)擴(kuò)展方法,因此您無法像使用該方法實(shí)際上屬于Assert類中的內(nèi)部版本一樣使用此方法。只需創(chuàng)建另一個(gè)名為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());
}
它的外觀和行為更像其余的單元測試語法。
- 3 回答
- 0 關(guān)注
- 2508 瀏覽
添加回答
舉報(bào)