问题描述
我正在尝试使用QTestLib为GUI应用程序编写单元测试.问题在于,其中一个插槽使用exec()
创建了一个模态对话框,但我发现无法与该对话框进行交互.
I am trying to write a unit test for a GUI application using the QTestLib. The problem is that one of the slots creates a modal dialog using exec()
and I found no possibility to interact with the dialog.
创建对话框的插槽连接到QAction.因此,第一个问题是当我在测试中触发QAction时,测试会阻塞,因为这会导致对exec()
的调用.因此,我尝试创建执行交互的QThread.但是,这没有帮助.
The slots which creates the dialog is connected to a QAction. So the first problem is that the test blocks when I trigger the QAction in the test since this results in the call to exec()
. Therefore, I tried creating a QThread that performs the interaction. However, this did not help.
我已经尝试过的东西(所有操作都在交互帮助器"线程中执行):
Things I already tried (all performed from within the "interaction helper" thread):
- 使用
QTest::keyClicks()
发送按键点击- 导致错误消息"QCoreApplication :: sendEvent():无法将事件发送到其他线程拥有的对象"
- Send key clicks using
QTest::keyClicks()
- Results in error message "QCoreApplication::sendEvent(): Cannot send events to objects owned by a different thread"
- 请参见下面的编辑
- See Edit below
- 请参见下面的编辑
- See Edit below
所以问题是:有什么方法可以通过编程方式与使用exec()
方法打开的模式对话框进行交互?
So the question is: Is there any way to interact programmatically with a modal dialog that was opened using the exec()
method?
编辑:实际上,方法3可行.问题是一个不同的问题:我将参数invokeMethod()
传递给交互帮助器"线程,由于某种原因,无法从该线程访问参数(我没有SEG错误,但它们只是空的).我想方法2也可以使用,我只是遇到了与方法3相同的问题,但我没有对此进行测试.
Actually, method 3 is working. The problem was a different one:I passed the arguments to invokeMethod()
to the "interaction helper" thread and for some reason, accessing the arguments did not work from that thread (I got no SEG errors but they were simply empty).I guess that method 2 is also working and I simply had the same problem as with method 3 but I didn't test that.
推荐答案
我在使用Qt库(用于GUI)的命令行应用程序中使用的解决方案是singleShot
,如暗示.在这种情况下,它看起来像这样:
The solution I use in command line applications which use Qt libraries meant for GUIs is the singleShot
, as this answer alludes. In those cases it looks like this:
QCoreApplication app(argc, argv);
// ...
QTimer::singleShot(0, &app, SLOT(quit()));
return app.exec();
所以在您的情况下,我想它看起来像这样:
So in your case I imagine it would look something like this:
QDialog * p_modalDialog = getThePointer(); // you will have to replace this with
// a real way of getting the pointer
QTimer::singleShot(0, p_modalDialog, SLOT(accept()));
p_modalDialog->exec(); // called somewhere else in your case
// but it will be automatically accepted.
这篇关于使用Qt测试的测试模式对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!