如何用Python和PyQt对我的GUI程序进行单元测试?

40 投票
3 回答
26937 浏览
提问于 2025-04-17 16:53

我听说单元测试是一种很好的方法,可以确保代码正常运行。

单元测试通常是给一个函数输入一些简单的数据,然后检查它的输出是否正确。但是,我该怎么测试用户界面呢?

我的程序是用PyQt写的。我应该选择PyUnit,还是Qt自带的QTest呢?

3 个回答

2

这里有一个很棒的教程,里面使用了pytest-qt:

https://www.youtube.com/watch?v=WjctCBjHvmA&ab_channel=AdamBemski https://github.com/adambemski/blog/tree/master/006_pytest_qt_GUI_testing

这个教程真的很简单,下面是教程中的代码:

import pytest

from PyQt5 import QtCore

import example_app


@pytest.fixture
def app(qtbot):
    test_hello_app = example_app.MyApp()
    qtbot.addWidget(test_hello_app)

    return test_hello_app


def test_label(app):
    assert app.text_label.text() == "Hello World!"


def test_label_after_click(app, qtbot):
    qtbot.mouseClick(app.button, QtCore.Qt.LeftButton)
    assert app.text_label.text() == "Changed!"
13

另外,如果你喜欢用 pytest 来工作,还有一个选择就是 pytest-qt

https://pytest-qt.readthedocs.io/en/latest/intro.html

这个工具可以帮助你测试 pyqtpyside 的应用程序,还能模拟用户的操作。下面是它文档中的一个小例子:

def test_hello(qtbot):
    widget = HelloWidget()
    qtbot.addWidget(widget)

    # click in the Greet button and make sure it updates the appropriate label
    qtbot.mouseClick(widget.button_greet, QtCore.Qt.LeftButton)

    assert widget.greet_label.text() == "Hello!"

38

这里有一个关于如何将Python的单元测试框架和QTest结合使用的不错教程,虽然原链接已经失效,但你可以通过WayBackMachine在这里找到页面。

这并不是说要选择其中一个,而是要把它们一起使用。 QTest的主要功能是模拟键盘输入、鼠标点击和鼠标移动。而Python的单元测试框架则负责其他的工作,比如准备测试环境、清理环境、启动测试、收集结果等等。

撰写回答