我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
这是测试方法的一个属性…你不使用Assert。看起来是这样的:
[ExpectedException(typeof(ExceptionType))]
public void YourMethod_should_throw_exception()
其他回答
这取决于您使用的测试框架?
例如,在MbUnit中,您可以用一个属性指定预期的异常,以确保您得到的是真正预期的异常。
[ExpectedException(typeof(ArgumentException))]
上面@Richiban提供的帮助器工作得很好,只是它不能处理抛出异常的情况,也不能处理预期的类型。以下说明:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace YourProject.Tests
{
public static class MyAssert
{
/// <summary>
/// Helper for Asserting that a function throws an exception of a particular type.
/// </summary>
public static void Throws<T>( Action func ) where T : Exception
{
Exception exceptionOther = null;
var exceptionThrown = false;
try
{
func.Invoke();
}
catch ( T )
{
exceptionThrown = true;
}
catch (Exception e) {
exceptionOther = e;
}
if ( !exceptionThrown )
{
if (exceptionOther != null) {
throw new AssertFailedException(
String.Format("An exception of type {0} was expected, but not thrown. Instead, an exception of type {1} was thrown.", typeof(T), exceptionOther.GetType()),
exceptionOther
);
}
throw new AssertFailedException(
String.Format("An exception of type {0} was expected, but no exception was thrown.", typeof(T))
);
}
}
}
}
你可以从Nuget下载一个包,使用:PM> Install-Package MSTestExtensions将Assert.Throws()语法以nUnit/xUnit的风格添加到MsTest。
高级指令:从BaseTest下载程序集并继承,您可以使用Assert.Throws()语法。
Throws实现的主要方法如下所示:
public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
try
{
task();
}
catch (Exception ex)
{
AssertExceptionType<T>(ex);
AssertExceptionMessage(ex, expectedMessage, options);
return;
}
if (typeof(T).Equals(new Exception().GetType()))
{
Assert.Fail("Expected exception but no exception was thrown.");
}
else
{
Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
}
}
披露:我整理了这个包。
更多信息:http://www.bradoncode.com/blog/2012/01/asserting-exceptions-in-mstest-with.html
在我正在做的一个项目中,我们有另一个解决方案。
首先,我不喜欢ExpectedExceptionAttribute,因为它确实考虑了导致异常的方法调用。
我用一个helper方法来代替它。
Test
[TestMethod]
public void AccountRepository_ThrowsExceptionIfFileisCorrupt()
{
var file = File.Create("Accounts.bin");
file.WriteByte(1);
file.Close();
IAccountRepository repo = new FileAccountRepository();
TestHelpers.AssertThrows<SerializationException>(()=>repo.GetAll());
}
HelperMethod
public static TException AssertThrows<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
Assert.Fail("Expected exception was not thrown");
return null;
}
很整洁,不是吗?)
在VS内置单元测试中,如果你只是想验证抛出了“任何异常”,但你不知道类型,你可以使用catch all:
[TestMethod]
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public void ThrowExceptionTest()
{
//...
}
推荐文章
- net HttpClient。如何POST字符串值?
- 何时使用Mockito.verify()?
- 我如何使一个方法的返回类型泛型?
- 在PHP单元测试执行期间,如何在CLI中输出?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 单元测试的一些常用命名约定是什么?