如何使用GoogleTest框架漂亮地打印QString? [英] How to pretty-print QString with GoogleTest framework?

查看:96
本文介绍了如何使用GoogleTest框架漂亮地打印QString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将GoogleTest(GTest)框架与Qt5应用程序结合使用.

I am using the GoogleTest (GTest) framework in conjunction with a Qt5 application.

每当使用QString参数的测试失败时,框架都会尝试打印所有涉及的值.但是,它不能自动处理外部类型(在这种情况下为Qt5的QString).

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

如何让GoogleTest自动打印漂亮的QString(无需每次都手动转换它们)?

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

推荐答案

Google测试指南介绍了通常如何

The GoogleTest Guide explains how you can in general teach the framework to handle custom types.

最后,要使GoogleTest能够与QStrings一起使用,需要添加以下代码片段:

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

此代码一定不能在测试装置的名称空间中,而必须在Qt名称空间中(或通常在其中定义应打印漂亮类型的名称空间中). 您必须在调用该特定类型的GoogleTest断言的所有翻译单元中都可以查看此代码,否则它将不会被使用(请参见注释).

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

结果,GoogleTest现在可以漂亮地打印QStrings了:

As a result GoogleTest now pretty prints QStrings:

您当然也可以添加一些引号,以使其更清楚地表明它来自QString:

You can of course also add some quotation marks to make it clearer that it comes from a QString:

*os << "\"" << qUtf8Printable(qString) << "\"";


来源:网络研讨会使用Google Test和Google Mock进行ICS Qt测试驱动的开发,高级咨询工程师Justin Noel


Source: Webinar ICS Qt Test-Driven Development Using Google Test and Google Mock by Justin Noel, Senior Consulting Engineer

这篇关于如何使用GoogleTest框架漂亮地打印QString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆