How to pretty-print QString with GoogleTest framework?

青春壹個敷衍的年華 提交于 2020-01-01 04:38:26

问题


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)?


回答1:


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



来源:https://stackoverflow.com/questions/42597726/how-to-pretty-print-qstring-with-googletest-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!