You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在类的单个函数中Mock两次文件打开操作的返回结果

问题原因及解决办法

问题原因

你这里的核心问题出在@patch装饰器的参数使用上:
当你写read_data=result()时,result()会在测试用例初始化阶段就被执行一次,直接返回了string1,之后read_data就被固定成这个字符串。后续每次调用f.read(),都会返回这个固定值,完全没用到你设置的side_effect迭代逻辑。

另外你对mock_open的用法也有误:mock_open的read_data参数是用来设置固定读取内容的,它本身不支持多次调用返回不同值的场景;要实现每次read()返回不同结果,得给mock出来的文件对象的read方法单独设置side_effect。

解决办法

这里提供两种可行的修正写法:

写法一:直接给mock文件的read方法设置side_effect

from unittest.mock import mock_open, patch

class TestABC:
    result1 = 'string1'
    result2 = 'string2'

    @patch("builtins.open", new_callable=mock_open)
    def test_parse_files(self, mock_file):
        # 给read方法绑定side_effect,实现每次调用返回不同值
        mock_file.return_value.read.side_effect = [self.result1, self.result2]
        item = ABC(['foo', 'bar'])
        assert item.store == ['string1', 'string2']

写法二:通过控制open的返回对象实现

from unittest.mock import Mock, patch

class TestABC:
    result1 = 'string1'
    result2 = 'string2'

    @patch("builtins.open")
    def test_parse_files(self, mock_open):
        # 创建两个mock文件对象,分别指定read返回值
        file_mock1 = Mock()
        file_mock1.read.return_value = self.result1
        file_mock2 = Mock()
        file_mock2.read.return_value = self.result2
        
        # 让open每次调用返回不同的文件mock对象
        mock_open.side_effect = [file_mock1, file_mock2]
        
        item = ABC(['foo', 'bar'])
        assert item.store == ['string1', 'string2']

两种写法的核心逻辑一致:让每次read()调用能迭代返回预设的不同值,而不是用read_data把读取内容固定死。

内容的提问来源于stack exchange,提问作者TheTeaRex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 15:47:06