Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 876
tangy Avatar asked Oct 29 '25 09:10

tangy


2 Answers

You can use EXPECT_EQ as a stream so: EXPECT_EQ(out.field1, val.field1) << m_csv_line; should do what you want.

like image 170
dj2 Avatar answered Oct 31 '25 02:10

dj2


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(...);
like image 26
PolyGlot Avatar answered Oct 31 '25 02:10

PolyGlot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!