问题描述
我正在尝试使用 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(): 无法将事件发送到不同线程拥有的对象"
- 见在下面编辑
- 请参阅下面的编辑
- 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.
推荐答案
我在使用用于 GUI 的 Qt 库的命令行应用程序中使用的解决方案是 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 Test 测试模式对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!