我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
有一个很棒的库叫做NFluent,它可以加速和简化你编写断言的方式。
编写抛出异常的断言非常简单:
[Test]
public void given_when_then()
{
Check.ThatCode(() => MethodToTest())
.Throws<Exception>()
.WithMessage("Process has been failed");
}
其他回答
好吧,我来总结一下大家之前说过的话…不管怎样,这是我根据好的答案构建的代码:)剩下要做的就是复制和使用…
/// <summary>
/// Checks to make sure that the input delegate throws a exception of type TException.
/// </summary>
/// <typeparam name="TException">The type of exception expected.</typeparam>
/// <param name="methodToExecute">The method to execute to generate the exception.</param>
public static void AssertRaises<TException>(Action methodToExecute) where TException : System.Exception
{
try
{
methodToExecute();
}
catch (TException) {
return;
}
catch (System.Exception ex)
{
Assert.Fail("Expected exception of type " + typeof(TException) + " but type of " + ex.GetType() + " was thrown instead.");
}
Assert.Fail("Expected exception of type " + typeof(TException) + " but no exception was thrown.");
}
在我正在做的一个项目中,我们有另一个解决方案。
首先,我不喜欢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;
}
很整洁,不是吗?)
作为一种替代方法,您可以尝试测试异常实际上是在您的测试中的下两行中抛出的。
var testDelegate = () => MyService.Method(params);
Assert.Throws<Exception>(testDelegate);
如果你正在使用MSTest,它最初没有ExpectedException属性,你可以这样做:
try
{
SomeExceptionThrowingMethod()
Assert.Fail("no exception thrown");
}
catch (Exception ex)
{
Assert.IsTrue(ex is SpecificExceptionType);
}
这取决于您使用的测试框架?
例如,在MbUnit中,您可以用一个属性指定预期的异常,以确保您得到的是真正预期的异常。
[ExpectedException(typeof(ArgumentException))]
推荐文章
- 我如何使一个方法的返回类型泛型?
- 在PHP单元测试执行期间,如何在CLI中输出?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?
- 单元测试的一些常用命名约定是什么?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 转换为值类型'Int32'失败,因为物化值为空