我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
Even though this is an old question, I would like to add a new thought to the discussion. I have extended the Arrange, Act, Assert pattern to be Expected, Arrange, Act, Assert. You can make an expected exception pointer, then assert it was assigned to. This feels cleaner than doing your Asserts in a catch block, leaving your Act section mostly just for the one line of code to call the method under test. You also don't have to Assert.Fail(); or return from multiple points in the code. Any other exception thrown will cause the test to fail, because it won't be caught, and if an exception of your expected type is thrown, but the it wasn't the one you were expecting, Asserting against the message or other properties of the exception help make sure your test won't pass inadvertently.
[TestMethod]
public void Bar_InvalidDependency_ThrowsInvalidOperationException()
{
// Expectations
InvalidOperationException expectedException = null;
string expectedExceptionMessage = "Bar did something invalid.";
// Arrange
IDependency dependency = DependencyMocks.Create();
Foo foo = new Foo(dependency);
// Act
try
{
foo.Bar();
}
catch (InvalidOperationException ex)
{
expectedException = ex;
}
// Assert
Assert.IsNotNull(expectedException);
Assert.AreEqual(expectedExceptionMessage, expectedException.Message);
}
其他回答
使用ExpectedException时要谨慎,因为它可能导致如下所示的几个陷阱:
Link
在这里:
http://xunit.github.io/docs/comparisons.html
如果需要测试异常,有一些不太受欢迎的方法。您可以使用try{act/fail}catch{assert}方法,该方法对于除了ExpectedException之外不直接支持异常测试的框架非常有用。
更好的选择是使用xUnit。NET,这是一个非常现代的、前瞻性的、可扩展的单元测试框架,它已经从所有其他错误中吸取了教训,并进行了改进。Assert就是这样一种改进。它为断言异常提供了更好的语法。
你可以找到xUnit。NET在github: http://xunit.github.io/
我不建议使用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。那么,我的方法仍然适用。
Even though this is an old question, I would like to add a new thought to the discussion. I have extended the Arrange, Act, Assert pattern to be Expected, Arrange, Act, Assert. You can make an expected exception pointer, then assert it was assigned to. This feels cleaner than doing your Asserts in a catch block, leaving your Act section mostly just for the one line of code to call the method under test. You also don't have to Assert.Fail(); or return from multiple points in the code. Any other exception thrown will cause the test to fail, because it won't be caught, and if an exception of your expected type is thrown, but the it wasn't the one you were expecting, Asserting against the message or other properties of the exception help make sure your test won't pass inadvertently.
[TestMethod]
public void Bar_InvalidDependency_ThrowsInvalidOperationException()
{
// Expectations
InvalidOperationException expectedException = null;
string expectedExceptionMessage = "Bar did something invalid.";
// Arrange
IDependency dependency = DependencyMocks.Create();
Foo foo = new Foo(dependency);
// Act
try
{
foo.Bar();
}
catch (InvalidOperationException ex)
{
expectedException = ex;
}
// Assert
Assert.IsNotNull(expectedException);
Assert.AreEqual(expectedExceptionMessage, expectedException.Message);
}
这是测试方法的一个属性…你不使用Assert。看起来是这样的:
[ExpectedException(typeof(ExceptionType))]
public void YourMethod_should_throw_exception()
既然您提到了使用其他测试类,那么比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用于异步方法测试。
推荐文章
- 如何使用Jest测试对象键和值是否相等?
- Linq-to-Entities Join vs GroupJoin
- 为什么字符串类型的默认值是null而不是空字符串?
- 在list中获取不同值的列表
- 组合框:向项目添加文本和值(无绑定源)
- 如何为ASP.net/C#应用程序配置文件值中的值添加&号
- 从System.Drawing.Bitmap中加载WPF BitmapImage
- 如何找出一个文件存在于c# / .NET?
- 为什么更快地检查字典是否包含键,而不是捕捉异常,以防它不?
- [DataContract]的命名空间
- string. isnullorempty (string) vs. string. isnullowhitespace (string)
- 完全外部连接
- 在foreach循环中编辑字典值
- 如何在xml文档中引用泛型类和方法
- 使用System.IO.Compression在内存中创建ZIP存档