Show failed function instead of macro in gtest

Viewed 50

currently I'm working on creating new tests using gtest. There are some cases where I use same groups of EXPECT_EQs, so I wrap them up in a function. And now when particular test failes, it prints out the line where EXPECT that failed was written instead of the line where wrapper function was called.

class TestSuite : public ::testing::Test
{
public:
    void wrapperForExpects(const std::string& str)
    {
        EXPECT_EQ(0, 0);
        EXPECT_EQ("zero", str);
    }
};

TEST_F(TestSuite, exampleName)
{
    std::string exampleVariable = "one";
    wrapperForExpects(exampleVariable);
}

In this example line number 7 will be printed out as failed to console, but I would like to see line number 14. How can I do that?

1 Answers

This is done by adding SCOPED_TRACE("exampleName") before the function call. This will create something similar to the stack trace in the output:

TEST_F(TestSuite, exampleName)
{
    SCOPED_TRACE("exampleName_scope");  // <------ Add this
    std::string exampleVariable = "one";
    wrapperForExpects(exampleVariable);
}

Live example: https://godbolt.org/z/nnzvjGc8P

See here for more examples.

Related