我正在学习单元测试。我想在打开文件时模拟return_value。但是我得到的是对象,而不是价值。
我看到许多关于使用mock_file()。readfile =…返回类的实例,而不是mock_file.readfile =…的帖子,但我无法使其正常工作。
我正在将python 3.6与pytest 4.6.3一起使用
# In file Test_ReadFromFile.py
import pytest
from pytest import raises
from unittest.mock import MagicMock
from LineReader import readFromFile
def test_returnsCorrectString(monkeypatch):
mock_file = MagicMock()
mock_file.readLine = MagicMock()
mock_file.readLine.return_value = "test line"
mock_open = MagicMock(return_value=mock_file)
monkeypatch.setattr("builtins.open", mock_open)
result = readFromFile("blah")
mock_open.assert_called_once_with("blah", 'r')
assert result == "test line"
# In file LineReader.py
import os
def readFromFile(filename):
infile = open(filename, "r")
line = infile.readline()
return line
我收到以下错误消息:
AssertionError: assert <MagicMock name='mock.readline()' id='2003604533768'> == 'test line'
任何想法是什么问题? 谢谢