'How can I customize Google Test failure messages?

I've written a Google Test like the one below which compares some computed values with the one expected stored in a CSV file.

class SampleTest : public ::testing::Test{
public:

    void setupFile(const std::string& filename) {
       // open csv file here
    }

    void checkRow(ComputedRowValue val) {
        CSVParsedOutput out;
        m_csv_f.readAndParseLine(out);
        EXPECT_EQ(out.field1, val.field1);
        EXPECT_EQ(out.field2, val.field2);
        EXPECT_EQ(out.field3, val.field3);
        m_csv_line++;
    }


protected:
    CSVFile m_csv_f; // CSV file with expected results
    int m_csv_line = 0;
};

This is going to be running across some huge file sizes and EXPECT_EQ when failing will only tell me which value mismatches. How can I override the error message output by EXPECT_EQ to also print m_csv_line?



Solution 1:[1]

If you have multiple assertions within single check consider using SCOPED_TRACE macro, described here. And instead of

EXPECT_EQ(out.field1, val.field1) << "text";
EXPECT_EQ(out.field2, val.field2) << "text";
EXPECT_EQ(out.field3, val.field3) << "text";

you can get

SCOPED_TRACE("text");
EXPECT_EQ(out.field1, val.field1);
EXPECT_EQ(out.field2, val.field2);
EXPECT_EQ(out.field3, val.field3);

That is even more helpful when you have complex output, like

EXPECT(...)<<"text"<<custom_class_var<<int_var;
EXPECT(...)<<"text"<<custom_class_var<<int_var;
EXPECT(...)<<"text"<<custom_class_var<<int_var;

It can be replaced with

std::stringstream message;
message<<"text"<<custom_class_var<<int_var;
SCOPED_TRACE(message.str());
EXPECT(...);
EXPECT(...);
EXPECT(...);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PolyGlot