Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty-print QString with GoogleTest framework?

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");

enter image description here

How can I get GoogleTest to pretty print QStrings automatically (= without having to manually convert them each time)?

like image 656
Philip Allgaier Avatar asked Mar 04 '17 15:03

Philip Allgaier


Video Answer


1 Answers

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: enter image description here

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

like image 107
Philip Allgaier Avatar answered Oct 01 '22 01:10

Philip Allgaier