您现在的位置是:网站首页> 编程资料编程资料
mstest实现类似单元测试nunit中assert.throws功能_实用技巧_
2023-05-24
235人已围观
简介 mstest实现类似单元测试nunit中assert.throws功能_实用技巧_
我们做单元测试NUnit中,有一个断言Assert.Throws很好用,但当我们使用MsTest时你需要这样写:
复制代码 代码如下:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void WriteToTextFile()
{
PDFUtility.WriteToTextFile("D:\\ACA.pdf", null);
}
现在让我们来扩展一下也实现类似成功能,增加一个类,代码如下:
复制代码 代码如下:
///
/// Useful assertions for actions that are expected to throw an exception.
///
public static class ExceptionAssert
{
///
/// Executes an exception, expecting an exception to be thrown.
/// Like Assert.Throws in NUnit.
///
/// The action to execute
///
public static Exception Throws(Action action)
{
return Throws(action, null);
}
///
/// Executes an exception, expecting an exception to be thrown.
/// Like Assert.Throws in NUnit.
///
/// The action to execute
/// The error message if the expected exception is not thrown
///
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.");
}
///
/// Executes an exception, expecting an exception of a specific type to be thrown.
/// Like Assert.Throws in NUnit.
///
/// The action to execute
///
public static T Throws
{
return Throws
}
///
/// Executes an exception, expecting an exception of a specific type to be thrown.
/// Like Assert.Throws in NUnit.
///
/// The action to execute
/// The error message if the expected exception is not thrown
///
public static T Throws
{
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'.
// Return the exception, in case the unit test wants to perform further assertions on it.
return actual;
}
// If we end up here, the expected exception of type 'T' was not thrown. Fail!
throw new AssertFailedException(message ?? String.Format("Expected exception of type {0} not thrown.", typeof(T)));
}
}
好了,现在我们在MsTest中可以这样了,看下面代码:
复制代码 代码如下:
[TestMethod]
public void WriteToTextFile2()
{
//Implement Assert.Throws in MSTest
ExceptionAssert.Throws
,"Output file path should not be null");
}
相关内容
- ASP.NET MVC3 实现全站重定向的简单方法_实用技巧_
- Jmail发送邮件与带附件乱码解决办法分享_实用技巧_
- .net后台代码调用前台JS的两种方式_实用技巧_
- .Net 文本框实现内容提示的实例代码(仿Google、Baidu)_实用技巧_
- 在aspx页面引用html页的写法_实用技巧_
- DataSet、DataTable、DataRow区别详解_实用技巧_
- asp.net中C#获取字符串中汉字的个数的具体实现方法_实用技巧_
- asp.net 备份和恢复数据库的方法示例_实用技巧_
- asp.net操作xml增删改示例分享_实用技巧_
- 压缩aspx页面删除多余空格的两种方法_实用技巧_
