Reputation: 81
How do you use mock unitest to mock filedialog.askopenfilename() or filedialog.saveasfilename()? The same question was answered in the following link for Python 2.x. Unittest Tkinter File Dialog
The solution does not work for Python 3.5 which is what I am using.
I tried both MagicMock and Patch from unittest and nothing was working. Please see my code below.
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)
Inside method1, it calls askopenfilename. I would like to make askopenfilename returns "".
I would greatly appreciated any help.
Upvotes: 2
Views: 480
Reputation: 81
I figure out how to do it. I need to specify the class name before 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 ''
Upvotes: 1