我可以知道 gtest EXPECT_NO_THROW (或 ASSERT_NO_THROW)内抛出了哪个异常吗?

San*_*osy 5 c++ testing automated-tests exception googletest

为了测试我的 C++ 项目,我使用 GoogleTest 框架。通常我可以使用以下语法来轻松调试故障:

EXPECT_TRUE(*statement*) << *debugMessage*;
Run Code Online (Sandbox Code Playgroud)

当我使用宏 EXPECT_NO_THROW (或 ASSERT_NO_THROW)时,我当然可能会这样做,但我无权访问宏本身内部抛出(和捕获)的异常对象,因此 debugMessage 无法告诉我任何有关它的信息。

是否可以以任何方式显示有关此异常的信息?

编辑

没有任何自定义函数/宏是不可能的。

Ric*_*ges 5

这是一种方法:

#include <exception>
#include <stdexcept>
#include <ostream>
#include <iostream> // for the test
#include <gtest/gtest.h>
namespace detail {

    struct unwrapper
    {
        unwrapper(std::exception_ptr pe) : pe_(pe) {}

        operator bool() const {
            return bool(pe_);
        }

        friend auto operator<<(std::ostream& os, unwrapper const& u) -> std::ostream&
        {
            try {
                std::rethrow_exception(u.pe_);
                return os << "no exception";
            }
            catch(std::runtime_error const& e)
            {
                return os << "runtime_error: " << e.what();
            }
            catch(std::logic_error const& e)
            {
                return os << "logic_error: " << e.what();
            }
            catch(std::exception const& e)
            {
                return os << "exception: " << e.what();
            }
            catch(...)
            {
                return os << "non-standard exception";
            }

        }
        std::exception_ptr pe_;
    };

}

auto unwrap(std::exception_ptr pe)
{
    return detail::unwrapper(pe);
}


template<class F>
::testing::AssertionResult does_not_throw(F&& f)
         {
             try {
                 f();
                 return ::testing::AssertionSuccess();
             }
             catch(...) {
                 return ::testing::AssertionFailure() << unwrap(std::current_exception());
             }
         };


TEST(a, b)
{
    ASSERT_TRUE(does_not_throw([] { throw std::runtime_error("i threw"); }));
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from a
[ RUN      ] a.b
/Users/rhodges/play/project/nod.cpp:66: Failure
Value of: does_not_throw([] { throw std::runtime_error("i threw"); })
  Actual: false (runtime_error: i threw)
Expected: true
[  FAILED  ] a.b (1 ms)
[----------] 1 test from a (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] a.b

 1 FAILED TEST
Run Code Online (Sandbox Code Playgroud)