我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?
当前回答
有一个很棒的库叫做NFluent,它可以加速和简化你编写断言的方式。
编写抛出异常的断言非常简单:
[Test]
public void given_when_then()
{
Check.ThatCode(() => MethodToTest())
.Throws<Exception>()
.WithMessage("Process has been failed");
}
其他回答
在使用NUnit的情况下,试试这个:
Assert.That(() =>
{
Your_Method_To_Test();
}, Throws.TypeOf<Your_Specific_Exception>().With.Message.EqualTo("Your_Specific_Message"));
FluentAssertions例子
为那些使用该库的用户添加一个使用FluentAssertions的示例。
// act
Action result = () => {
sut.DoSomething();
};
// assert
result.Should().Throw<Exception>();
异步的例子
// act
Func<Task> result = async () => {
await sut.DoSomethingAsync();
};
// assert
await result.Should().ThrowAsync<Exception>();
如果你正在使用MSTest,它最初没有ExpectedException属性,你可以这样做:
try
{
SomeExceptionThrowingMethod()
Assert.Fail("no exception thrown");
}
catch (Exception ex)
{
Assert.IsTrue(ex is SpecificExceptionType);
}
作为一种替代方法,您可以尝试测试异常实际上是在您的测试中的下两行中抛出的。
var testDelegate = () => MyService.Method(params);
Assert.Throws<Exception>(testDelegate);
好吧,我来总结一下大家之前说过的话…不管怎样,这是我根据好的答案构建的代码:)剩下要做的就是复制和使用…
/// <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.");
}