Class Skeleton
Class Skeleton

Reputation: 3073

How to assert that an exception has not been raised?

I am using the unit testing features in Visual Studio 2013 for my application.

I am trying to write a test for a class whereby you pass in a specific object to the constructor, and depending on the state of the object passed, an exception may be thrown.

I have written stubs for each object state, and have written test cases for the scenarios where the constructor will throw an exception as follows:

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

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

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

How should I approach a scenario where I want to pass a valid stub and simply assert that no exception was raised? I want to be purely concerned with a specific MyException not being thrown (rather than any exception).

I have hacked together a test method as follows but not sure if there is a simply "1 line" approach that would fit my needs:

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

I am not confident I need to also fail "any exception" being raised, as this should(?) be picked up by the test runner (i.e. fail the test). Along the same reasoning, would the following essentially be the same test:

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

    // act
    const Foo foo(stub);

    // assert
    // no exception
}

Upvotes: 1

Views: 2552

Answers (1)

Class Skeleton
Class Skeleton

Reputation: 3073

I used the following test method to show that a constructor doesn't throw an exception:

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

    // act
    const Foo foo(stub);

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

When an exception is raised the test automatically fails. The exception details are given in the failure message.

When no exception is raised the test will pass as I am asserting true == true.

Upvotes: 1

Related Questions