GTest 的 C++11 问题

标签 c++ c++11 googletest

我正在为应用程序编写单元测试。我在构造函数中有一些异常,所以我这样写:

TEST(Tablier, ConstructeurParamInvalide2)
{
    ASSERT_THROW(Tablier t_tablier{10, 65} , PreconditionException);
}

当我写这个的时候,似乎宏 ASSERT_THROW 不满足,测试失败。这是宏扩展:

switch (0) case 0: default: \
  if (::testing::internal::ConstCharPtr gtest_msg = "") { \
    bool gtest_caught_expected = false; \
    try { \
      if (::testing::internal::AlwaysTrue()) { Tablier t_tablier{10; }; \
    } \
    catch (65} const&) { \
      gtest_caught_expected = true; \
    } \
    catch (...) { \
      gtest_msg.value = \
          "Expected: " "Tablier t_tablier{10" " throws an exception of type " \
          "65}" ".\n  Actual: it throws a different type."; \
      goto gtest_label_testthrow_76; \
    } \
    if (!gtest_caught_expected) { \
      gtest_msg.value = \
          "Expected: " "Tablier t_tablier{10" " throws an exception of type " \
          "65}" ".\n  Actual: it throws nothing."; \
      goto gtest_label_testthrow_76; \
    } \
  } else \
    gtest_label_testthrow_76: \
      return ::testing::internal::AssertHelper(::testing::TestPartResult::kFatalFailure, "/home/eric/Programming/cpp/Puissance4/pxTestsUnitaires/tests/test_Tablier.cpp", 76, gtest_msg.value) \
    = ::testing::Message()

注意 Tablier t_tablier{10; }; 相反,如果我这样写:

TEST(Tablier, ConstructeurParamInvalide2)
{
    ASSERT_THROW(Tablier t_tablier(10, 65) , PreconditionException);
}

宏运行良好,测试通过。我的项目和编译器针对 C++11 配置,许多其他测试使用 C++11 语法通过。知道可能是什么问题吗?

最佳答案

这应该有效:

ASSERT_THROW(Tablier t_tablier(10, 65) , PreconditionException);
ASSERT_THROW(Tablier (10, 65) , PreconditionException);

由于宏扩展认为10到65之间的逗号是宏参数分隔符。括号是用来告诉编译器哪个是定界符。

来自 cpp.replace

The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of arguments for the function-like macro. The individual arguments within the list are separated by comma preprocessing tokens, but comma preprocessing tokens between matching inner parentheses do not separate arguments.

关于GTest 的 C++11 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877502/

相关文章:

c++ - 未找到 Xcode 4.5 和 C++11 header

c++ - 对 C++ 基类的模糊函数调用

c++ - 为什么当我在谷歌测试程序中定义一个 const 字符串时会发生段错误?

c++ - 控制程序的输出

C++ 从文件中计算字符数组中的特定计数器

c++ - 这个程序调用带有参数包的函数指针有什么问题?

c++ - googlemock 可以从同一类的其他方法调用中模拟方法调用吗?

c++ - 如何使 gtest 在遇到断言时不完全关闭? (不是测试断言)

c++ - QThreadPool 示例

android - ARM 上的快速调用(Android NDK)