国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

mstest實現類似單元測試nunit中assert.throws功能

2024-07-10 12:43:49
字體:
來源:轉載
供稿:網友

我們做單元測試NUnit中,有一個斷言Assert.Throws很好用,但當我們使用MsTest時你需要這樣寫:
代碼如下:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void WriteToTextFile()
{
PDFUtility.WriteToTextFile("D://ACA.pdf", null);
}

現在讓我們來擴展一下也實現類似成功能,增加一個類,代碼如下:
代碼如下:
/// <summary>
/// Useful assertions for actions that are expected to throw an exception.
/// </summary>
public static class ExceptionAssert
{
/// <summary>
/// Executes an exception, expecting an exception to be thrown.
/// Like Assert.Throws in NUnit.
/// </summary>
/// <param name="action">The action to execute</param>
/// <returns>The exception thrown by the action</returns>
public static Exception Throws(Action action)
{
return Throws(action, null);
}

/// <summary>
/// Executes an exception, expecting an exception to be thrown.
/// Like Assert.Throws in NUnit.
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="message">The error message if the expected exception is not thrown</param>
/// <returns>The exception thrown by the action</returns>
public static Exception Throws(Action action, string message)
{
try
{
action();
}
catch (Exception ex)
{
// The action method has thrown the expected exception.
// Return the exception, in case the unit test wants to perform further assertions on it.
return ex;
}

// If we end up here, the expected exception was not thrown. Fail!
throw new AssertFailedException(message ?? "Expected exception was not thrown.");
}

/// <summary>
/// Executes an exception, expecting an exception of a specific type to be thrown.
/// Like Assert.Throws in NUnit.
/// </summary>
/// <param name="action">The action to execute</param>
/// <returns>The exception thrown by the action</returns>
public static T Throws<T>(Action action) where T : Exception
{
return Throws<T>(action, null);
}

/// <summary>
/// Executes an exception, expecting an exception of a specific type to be thrown.
/// Like Assert.Throws in NUnit.
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="message">The error message if the expected exception is not thrown</param>
/// <returns>The exception thrown by the action</returns>
public static T Throws<T>(Action action, string message) where T : Exception
{
try
{
action();
}
catch (Exception ex)
{
T actual = ex as T;
if (actual == null)
{
throw new AssertFailedException(message ?? String.Format("Expected exception of type {0} not thrown. Actual exception type was {1}.", typeof(T), ex.GetType()));
}

// The action method has thrown the expected exception of type 'T'.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 庆阳市| 同江市| 日照市| 伊吾县| 泗洪县| 秦皇岛市| 逊克县| 鹿泉市| 肥西县| 彝良县| 阜新| 司法| 广河县| 阳江市| 宁安市| 静安区| 本溪| 江油市| 泉州市| 孙吴县| 化隆| 合江县| 嘉峪关市| 福清市| 兴海县| 木兰县| 康马县| 黔东| 宿迁市| 宜兴市| 涟源市| 鹤山市| 泾川县| 原阳县| 宁乡县| 石台县| 沧州市| 凤冈县| 萝北县| 峨眉山市| 秭归县|