我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
我不建议使用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。那么,我的方法仍然适用。
其他回答
既然您提到了使用其他测试类,那么比ExpectedException属性更好的选择是使用Shoudly的Should.Throw。
Should.Throw<DivideByZeroException>(() => { MyDivideMethod(1, 0); });
假设我们有一个需求,客户必须有一个地址才能创建订单。如果不是,CreateOrderForCustomer方法应该导致一个ArgumentException。那么我们可以这样写:
[TestMethod]
public void NullUserIdInConstructor()
{
var customer = new Customer(name := "Justin", address := null};
Should.Throw<ArgumentException>(() => {
var order = CreateOrderForCustomer(customer) });
}
这比使用ExpectedException属性更好,因为我们明确了应该抛出错误的内容。这使得测试中的需求更加清晰,并且在测试失败时更容易诊断。
注意这里还有一个Should。ThrowAsync用于异步方法测试。
在使用NUnit的情况下,试试这个:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
我知道这个帖子很老了,有很多很好的答案,但值得一提的是,局部函数可以以一种非常简单的方式提供帮助。
//Arrange
//Act
void LocalFunction() => mr.ActualMethod(params);
//Assert
Assert.Throws<Exception>(LocalFunction);
在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?
- 如何分裂()一个分隔字符串到一个列表<字符串>