我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
在使用NUnit的情况下,试试这个:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
其他回答
这取决于您使用的测试框架?
例如,在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))
);
}
}
}
}
这适用于Visual Studio Team Test(又名MSTest) 在处理数据库或http事务时。系统应该在某处抛出异常,使用Assert.ThrowExceptionAsync<>()将捕获您的throw事件。(在这些情况下,Assert.ThrowException<>()不会捕获异常)。
[TestMethod]
public void Invalid_Input_UserName_Should_Throw_Exception()
{
await Assert.ThrowExceptionAsync<ExpectedExceptionType>(()=> new LogonInfo(InvalidInputInUserNameFormat,"P@ssword"));
}
在VS内置单元测试中,如果你只是想验证抛出了“任何异常”,但你不知道类型,你可以使用catch all:
[TestMethod]
[ExpectedException(typeof(Exception), AllowDerivedTypes = true)]
public void ThrowExceptionTest()
{
//...
}
我不建议使用ExpectedException属性(因为它约束太大,容易出错),也不建议在每个测试中编写一个try/catch块(因为它太复杂,容易出错)。使用设计良好的断言方法——可以由您的测试框架提供,也可以自己编写。下面是我写的和用的。
public static class ExceptionAssert
{
private static T GetException<T>(Action action, string message="") where T : Exception
{
try
{
action();
}
catch (T exception)
{
return exception;
}
throw new AssertFailedException("Expected exception " + typeof(T).FullName + ", but none was propagated. " + message);
}
public static void Propagates<T>(Action action) where T : Exception
{
Propagates<T>(action, "");
}
public static void Propagates<T>(Action action, string message) where T : Exception
{
GetException<T>(action, message);
}
public static void Propagates<T>(Action action, Action<T> validation) where T : Exception
{
Propagates(action, validation, "");
}
public static void Propagates<T>(Action action, Action<T> validation, string message) where T : Exception
{
validation(GetException<T>(action, message));
}
}
使用示例:
[TestMethod]
public void Run_PropagatesWin32Exception_ForInvalidExeFile()
{
(test setup that might propagate Win32Exception)
ExceptionAssert.Propagates<Win32Exception>(
() => CommandExecutionUtil.Run(Assembly.GetExecutingAssembly().Location, new string[0]));
(more asserts or something)
}
[TestMethod]
public void Run_PropagatesFileNotFoundException_ForExecutableNotFound()
{
(test setup that might propagate FileNotFoundException)
ExceptionAssert.Propagates<FileNotFoundException>(
() => CommandExecutionUtil.Run("NotThere.exe", new string[0]),
e => StringAssert.Contains(e.Message, "NotThere.exe"));
(more asserts or something)
}
笔记
返回异常而不是支持验证回调是一个合理的想法,只是这样做会使这个断言的调用语法与我使用的其他断言非常不同。
与其他人不同,我使用“propagates”而不是“throws”,因为我们只能测试异常是否从调用中传播。我们不能直接测试是否抛出了异常。但我想你可以把投掷想象成:被扔出去而没有被接住。
最后认为
在切换到这种方法之前,我考虑过在测试只验证异常类型时使用ExpectedException属性,在需要更多验证时使用try/catch块。但是,我不仅要考虑在每个测试中使用哪种技术,而且随着需求的变化将代码从一种技术更改为另一种技术也不是一件简单的工作。使用一种一致的方法可以节省脑力。
总而言之,这种方法具有易用性、灵活性和健壮性(很难做错)。
更新
我的方法对于mstest V2来说不再有价值了,它似乎已经在2018年问世了。使用Assert.ThrowsException。
除非你一直在使用旧版本的mstest。那么,我的方法仍然适用。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- 单元测试反模式目录
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>