python3.5的Unittest Tkinter文件对话框

2024-03-28 11:34:00 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用mock unitest进行模拟文件对话框.askopenfilename()或filedialog.saveasfilename()? Python2.x的以下链接也回答了相同的问题。 Unittest Tkinter File Dialog

这个解决方案不适用于我正在使用的python3.5。在

我尝试了unittest的MagicMock和Patch,但都没用。请看我下面的代码。在

from tkinter.filedialog import *
from unittest.mock import MagicMock
from unittest.mock import patch

# @patch(filedialog.askopenfilename)
def test1(self):
    try:
        filedialog.askopenfilename = MagicMock(return_value="")
        app = class1()
        app.method1()
    except ValueError as e:
        print(e)

@patch(filedialog.askopenfilename)
def test2(self, mock1):
    try:
        # filedialog.askopenfilename = MagicMock(return_value="")
        app = class1()  
        app.method1()  #method1 has filedialog.askopenfilename in it
    except ValueError as e:
        print(e)

在method1中,它调用askopenfilename。我想使askopenfilename返回“”。在

我将非常感谢你的帮助。在


Tags: fromimportselfappreturnvaluedefunittest
1条回答
网友
1楼 · 发布于 2024-03-28 11:34:00

我知道怎么做。我需要在askopenfilename之前指定类名。在

    from unittest.mock import Mock
    class1.askopenfilename = Mock(return_value='')
    # Inside class1, method1 uses askopenfilename to open up file dialog box
    class1.method1()   # method1 will call Mock(return_value='') instead of askopenfilename and return ''

相关问题 更多 >