小编kyn*_*org的帖子

模拟实例属性

请帮助我理解为什么以下不起作用。特别是 - 被测试类的实例属性对 Python 不可见unittest.Mock

在下面的示例中,bar实例属性不可访问。返回的错误是:

AttributeError: <class 'temp.Foo'> does not have the attribute 'bar'
Run Code Online (Sandbox Code Playgroud)
import unittest
from unittest.mock import patch

class Foo:
    def __init__(self):
        super().__init__(self)
        self.bar = some_external_function_returning_list()

    def do_someting(self):
        calculate(self.bar)

class TestFoo(unittest.TestCase):

    @patch('temp.Foo.bar')
    def test_do_something(self, patched_bar):
        patched_bar.return_value = ['list_elem1', 'list_elem2']
Run Code Online (Sandbox Code Playgroud)

python unit-testing mocking

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

mocking ×1

python ×1

unit-testing ×1