如何断言未引发异常?

How to assert that an exception has not been raised?

我正在为我的应用程序使用 Visual Studio 2013 中的单元测试功能。

我正在尝试为 class 编写一个测试,您将特定对象传递给构造函数,根据传递的对象的状态,可能会抛出异常。

我已经为每个对象状态编写了存根,并为构造函数会抛出异常的场景编写了测试用例,如下所示:

TEST_METHOD(constructor_ExceptionRaised)
{
    // arrange
    const InvalidStub stub;

    // act
    auto act = [stub] { const Foo foo(stub); };

    // assert
    Microsoft::VisualStudio::CppUnitTestFramework::Assert::ExpectException
        <MyException>(act);
}

我应该如何处理我想要传递有效存根并简单地断言没有引发异常的场景?我想纯粹关心一个特定的 MyException 没有被抛出(而不是任何异常)。

我已经编写了如下测试方法,但不确定是否有适合我需要的简单“1 行”方法:

TEST_METHOD(constructor_NoException)
{
    // arrange
    const ValidStub stub;

    try
    {
        // act
        const Foo foo(stub);
    }

    // assert
    catch (MyException e)
    {
        Microsoft::VisualStudio::CppUnitTestFramework::Assert::Fail();
    }
    catch (...)
    {
        Microsoft::VisualStudio::CppUnitTestFramework::Assert::Fail();
    }
}

我不确定我是否也需要失败 "any exception" 被提出,因为这应该(?)被测试运行者拾取(即测试失败)。按照同样的推理,以下是否本质上是相同的测试:

TEST_METHOD(constructor_NoException)
{
    // arrange
    const ValidStub stub;

    // act
    const Foo foo(stub);

    // assert
    // no exception
}

我使用了以下测试方法来证明构造函数不会抛出异常:

TEST_METHOD(constructor_NoException)
{
    // arrange
    const ValidStub stub;

    // act
    const Foo foo(stub);

    // assert
    Microsoft::VisualStudio::CppUnitTestFramework::Assert::IsTrue(true);
}

引发异常时,测试会自动失败。异常详细信息在失败消息中给出。

当没有出现异常时,测试将通过,因为我断言 true == true