I am using the GoogleTest (GTest) framework in conjunction with a Qt5 application.
Whenever a test fails using a QString argument, the framework tries to print all the involved values. However, it cannot automatically handle foreign types (Qt5's QString in this case).
QString test = "Test";
ASSERT_EQ(test, "Value");
How can I get GoogleTest to pretty print QStrings automatically (= without having to manually convert them each time)?
The GoogleTest Guide explains how you can in general teach the framework to handle custom types.
In the end, the following code snippet is all that needs to be added for GoogleTest being able to work with QStrings:
QT_BEGIN_NAMESPACE
inline void PrintTo(const QString &qString, ::std::ostream *os)
{
*os << qUtf8Printable(qString);
}
QT_END_NAMESPACE
This code MUST NOT be in the namespace of your test fixtures, but must be in the Qt namespace (or in general in the namespace where the type that should be pretty-printed is defined in). This code MUST also be viewable from all translation units where you call a GoogleTest assertion on that particular type, otherwise it will not get used (see comments).
As a result GoogleTest now pretty prints QStrings:
You can of course also add some quotation marks to make it clearer that it comes from a QString:
*os << "\"" << qUtf8Printable(qString) << "\"";
Source: Webinar ICS Qt Test-Driven Development Using Google Test and Google Mock by Justin Noel, Senior Consulting Engineer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With