How can I customize Google Test failure messages?
Asked Answered
B

2

3

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?

Bridgid answered 20/12, 2018 at 19:51 Comment(0)
B
8

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

Bessette answered 20/12, 2018 at 20:45 Comment(0)
H
3

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(...);
Hexateuch answered 4/3, 2022 at 9:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.