我如何使用Assert(或其他测试类)来验证在使用MSTest/Microsoft.VisualStudio.TestTools.UnitTesting时抛出了异常?


当前回答

如果你使用NUNIT,你可以这样做:

Assert.Throws<ExpectedException>(() => methodToTest());

也可以存储抛出的异常以便进一步验证:

ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest());
Assert.AreEqual( "Expected message text.", ex.Message );
Assert.AreEqual( 5, ex.SomeNumber);

参见:http://nunit.org/docs/2.5/exceptionAsserts.html

其他回答

使用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/

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);
}

我最喜欢的实现方法是编写一个名为Throws的方法,并像使用其他Assert方法一样使用它。不幸的是,.NET不允许你编写静态扩展方法,所以你不能像使用Assert类中的构建一样使用这个方法;创建另一个MyAssert或类似的东西。类看起来像这样:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace YourProject.Tests
{
    public static class MyAssert
    {
        public static void Throws<T>( Action func ) where T : Exception
        {
            var exceptionThrown = false;
            try
            {
                func.Invoke();
            }
            catch ( T )
            {
                exceptionThrown = true;
            }

            if ( !exceptionThrown )
            {
                throw new AssertFailedException(
                    String.Format("An exception of type {0} was expected, but not thrown", typeof(T))
                    );
            }
        }
    }
}

这意味着你的单元测试看起来是这样的:

[TestMethod()]
public void ExceptionTest()
{
    String testStr = null;
    MyAssert.Throws<NullReferenceException>(() => testStr.ToUpper());
}

它的外观和行为更像单元测试语法的其余部分。

如果你使用NUNIT,你可以这样做:

Assert.Throws<ExpectedException>(() => methodToTest());

也可以存储抛出的异常以便进一步验证:

ExpectedException ex = Assert.Throws<ExpectedException>(() => methodToTest());
Assert.AreEqual( "Expected message text.", ex.Message );
Assert.AreEqual( 5, ex.SomeNumber);

参见:http://nunit.org/docs/2.5/exceptionAsserts.html

您可以通过简单的一行代码来实现这一点。

如果你的foo.bar()操作是异步的:

await Assert.ThrowsExceptionAsync<Exception>(() => foo.bar());

如果foo.bar()不是异步的

Assert.ThrowsException<Exception>(() => foo.bar());