BobMorane BobMorane - 2 days ago 5
C++ Question

C++11 issue with GTest

I am writing unit tests for an application. I have some exceptions in a constructor, so I wrote this:

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


When I write this, it seems the macro ASSERT_THROW is not satisfied and the test fails. Here is the macro expansion:

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


Notice the
Tablier t_tablier{10; };
Instead, if I write this:

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


The macro works fine and the test passes. My project and compiler are configured for C++11, and many other tests pass using C++11 syntax. Any idea what could be the issue?

Regards

Answer

This should work:

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

since the macro expansion think the comma between 10 and 65 is macro parameter delimiter. The parentheses is there to tell compiler which one is delimiter.

From 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.

Comments