首页 > 解决方案 > python unittest验证按钮单击

问题描述

我无法使此按钮单击验证工作,我的测试有什么问题?

模块最小示例.py:

from PyQt5.QtWidgets import QPushButton, QDialog
from PyQt5.QtCore import pyqtSlot

class App(QDialog):
    def __init__(self):
        super().__init__()
        self.button = QPushButton('PyQt5 button', self)
        self.button.clicked.connect(self.on_click)
        self.show()

    @pyqtSlot()
    def on_click(self):
        print('button clicked')

模块 test_minimalExample.py
from unittest import TestCase
from unittest.mock import patch as patch

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtTest import QTest

import minimalExample

class TestApp(TestCase):

    def setUp(self):
        self.ctx = QApplication([])

    def test_on_click(self):
        with patch.object(minimalExample.App, 'on_click') as mock:
            app = minimalExample.App()
            QTest.mouseClick(app.button, Qt.LeftButton)
            self.assertTrue(mock.assert_called())

我可以在输出中看到我的按钮被点击,但我也得到:
AssertionError: Expected 'on_click' to have been called。

标签: pythonunit-testingbuttonmockingpyqt5

解决方案


通过稍微调整 test_on_click 方法,它现在适用于我的最小示例:

def test_on_click(self):
    with mock.patch('minimalExample.App.on_click') as clickCheck:
        app = minimalExample.App()
        QTest.mouseClick(app.button, Qt.LeftButton)
        self.assertTrue(clickCheck.called)

推荐阅读