python - 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。
解决方案
通过稍微调整 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)
推荐阅读
- linux - EasyApache4 更新覆盖 htaccess 文件
- python - Instagram 媒体链接上的 Python 请求返回 Not Found 错误
- css - 为什么绝对定位元素会查看其兄弟元素?
- go - 运行 golang 调试器时,VSCode 调试不在 VARIABLES 区域中显示映射值
- python - 使用 Dask DataFrame loc 更改列值
- css - 有没有办法通过css为选定单元格的行着色?
- graphql - 创建包含不同其他项目数组的项目的突变
- javascript - 如何使用复选框实现多选和单选?
- maven - 根据 PROD 或 TEST 在 NetBeans 中使用不同的 persistence.xml
- oracle - 如何通过 SQL 获取 UDT 成员?