Reputation: 6260
I have some code which uses WinAPI to get the title and classname of a window from it's handle using GetWindowTextW
and GetClassNameW
. I would like to create a unit test for this code using Qt to create a temporary window, run my code against it, and then close the window. However I'm unsure how to go about doing this in a simple way. For example, I could create the window as follows:
#include "QtWidgets\qapplication.h"
#include "QtWidgets\qtextedit.h"
int argc = 1;
char* argv[1];
QApplication app(argc, &argv[0]);
QTextEdit textEdit;
textEdit.show();
app.exec(;)
// Rest of my unit test here
However at that point the QApplication object enters it's event loop and assumes control of my unit test until I close the window. What is the best way to allow my unit test to continue operating on the window? Should I create a separate thread for the window? Being a unit test, I would like to keep it as simple as possible.
This question is intended to be unit test framework independent, but in case it matters, I'm using UnitTest++.
Upvotes: 0
Views: 856
Reputation: 2614
reasonably working example code for doing this is in this related question's answer: Qt event loop and unit testing?
Upvotes: 0
Reputation: 777
In my automated Qt tests, I generally skip the use of QApplication::exec in favour of using QCoreApplication::hasPendingEvents and QCoreApplication::processEvents - this lets you do some prep work, flush the event queue (so Qt gets a chance to actually show your window), do some more work, let Qt handle any additional events that this has thrown up, etc; it's a very handy approach for achieving the fine-grained control you need when you want to exercise small pieces of logic.
Upvotes: 0
Reputation: 5355
You won't be able to create a separate thread, since all Qt gui objects have to be in the main thread, you can only use signals/slot mechanism to interact with gui objects from other threads.
I think the simplest would be to subclass QTextEdit, implement public slot UnitTest(), and modify your test as follows:
#include "QtWidgets\qapplication.h"
#include "QtWidgets\qtextedit.h"
#include "MyTextEdit.h"
#include <QTimer>
int argc = 1;
char* argv[1];
QApplication app(argc, &argv[0]);
my_QTextEdit textEdit;
textEdit.show();
QTimer::singleShot(&my_QTextEdit,SLOT(UnitTest()),0);
app.exec();
This gives you an entry point to my_QTextEdit::UnitTest() after QApplication is properly instantiated and event loop is running. Or, you can implement your own class inherited from QObject, create public slot, create that object prior to running app.exec() (passing to it pointer to QTextEdit if necessary) ; and connect to the slot the same way - whatever suits your needs better.
Upvotes: 1