3 回答

TA貢獻1860條經驗 獲得超8個贊
對于“ 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");
}

TA貢獻1844條經驗 獲得超8個贊
實現此目的的首選方法是編寫一個稱為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());
}
它的外觀和行為更像其余的單元測試語法。
- 3 回答
- 0 關注
- 2512 瀏覽
添加回答
舉報