看完這個:How do I mock an open used in a with statement (using the Mock framework in Python)?Python的模擬 - 懲戒幾個開放
我可以在使用嘲笑open函數在python:
with patch(open_name, create=True) as mock_open:
mock_open.return_value = MagicMock(spec=file)
m_file = mock_open.return_value.__enter__.return_value
m_file.read.return_value = 'text1'
diffman = Diffman()
diffman.diff(path1, path2)
它運作良好時,我的測試方法使用一個公開聲明。這裏是我測試的方法:
def diff(self, a, b):
with open(a, 'r') as old:
with open(b, 'r') as new:
oldtext = old.read()
newtext = new.read()
oldtext和newtext的值是相同的(這裏是'text1')。
我希望oldtext有'text1',newtext有'text2'。
我該怎麼做?