Sample project started as a QT Console Application and contains main.cpp, TestString.h and TestString.cpp files.
Project Directory Structure in Qt Creator IDE :

LogQTestOutputToFile.pro is the project configuration file and contains:
QT += testlib core
TARGET = LogQTestOutputToFile
TEMPLATE = app
SOURCES += main.cpp \
TestString.cpp
HEADERS += TestString.h
QT += testlib
line which is used to include testlib dependencies into project.
TestString.h file contains private slots which are aimed to test mainly toUpper() behavior of String class.
#include <QtTest/QtTest>
#include <QString>
#include <QObject>
class TestString: public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void toUpper();
void cleanupTestCase();
};
initTestCase() and cleanupTestCase() private slots are executed by the testing framework and used to initialize and release resources; respectively.
TestString.cpp file contains implementation details for the private slots declared in TestString.h file.
#include "TestString.h"
void TestString::initTestCase()
{
qDebug("called before everything else, initialize your resources");
}
void TestString::toUpper()
{
QString str = "Hello";
QCOMPARE(str.toUpper(), QString("HELLO"));
}
void TestString::cleanupTestCase()
{
qDebug("called after toUpper(), release allocated resources here");
}
Because this a QT Console Application, main.cpp file contains only main() function which calls QTest::qExec(&testString, testCmd) function to execute testfunctions in the specified test object.
#include <QApplication>
#include <QStringList>
#include <QDir>
#include "TestString.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStringList testCmd;
QDir qtestLogDir;
qtestLogDir.mkdir("UnitTest_Results");
testCmd<<" "<<"-o"<<"UnitTest_Results/QTestString_log.txt";
TestString testString;
QTest::qExec(&testString, testCmd);
return a.exec();
}
When you run the application, test execution output is displayed at QT Creator Application Output Window. In order to redirect testfunction output to specified log file; output directory and log file name information are passed as argument to QTest::qExec(&testString, testCmd) function.
testCmd<<" "<<"-o"<<"UnitTest_Results/QTestString_log.txt";
command line argument redirects output to UnitTest_Results/QTestString_log.txt file.
QTestString_log.txt file can be found under LogQTestOutputToFile/UnitTest_Results folder.
No comments:
Post a Comment