Test a specific exception type is thrown AND the exception has the right properties

前端 未结 10 1666
梦如初夏
梦如初夏 2020-12-24 01:55

I want to test that MyException is thrown in a certain case. EXPECT_THROW is good here. But I also want to check the exception has a specific state

10条回答
  •  一向
    一向 (楼主)
    2020-12-24 02:26

    Jeff Langr describes a good approach in his book, Modern C++ Programming with Test-Driven Development:

    If your [testing] framework does not support a single-line declarative assert that ensures an exception is thrown, you can use the following structure in your test:

        TEST(ATweet, RequiresUserNameToStartWithAnAtSign) {
            string invalidUser("notStartingWith@");
            try {
                Tweet tweet("msg", invalidUser);
                FAIL();
            }
            catch(const InvalidUserException& expected) {}
        }
    

    [...] You might also need to use the try-catch structure if you must verify any postconditions after the exception is thrown. For example, you may want to verify the text associated with the thrown exception object.

        TEST(ATweet, RequiresUserNameToStartWithAtSign) {
            string invalidUser("notStartingWith@");
            try {
                Tweet tweet("msg", invalidUser);
                FAIL();
            }
            catch(const InvalidUserException& expected) {
                ASSERT_STREQ("notStartingWith@", expected.what());
            }
        }
    

    (p.95)

    This is the approach I've used, and have seen in practice elsewhere.

    Edit: As has been pointed out by @MikeKinghan, this doesn't quite match the functionality provided by EXPECT_THROW; the test doesn't fail if the wrong exception is thrown. An additional catch clause could be added to address this:

    catch(...) {
        FAIL();
    }
    

提交回复
热议问题