模拟实例属性

kyn*_*org 7 python unit-testing mocking

请帮助我理解为什么以下不起作用。特别是 - 被测试类的实例属性对 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)

che*_*ner 13

修补用于修改名称或属性查找。在这种情况下,类没有属性。bartemp.Foo

如果目的是修补实例变量,则需要现有实例来修改

def test(self):
    f = Foo()
    with patch.object(f, 'bar', 3):
        self.assertEqual(f.bar, 3)
Run Code Online (Sandbox Code Playgroud)

或者您可能想修补首先初始化实例属性的函数调用。

def test(self):
    with patch('some_external_function_returning_list', return_value=3):
        f = Foo()
    self.assertEqual(f.bar, 3)
Run Code Online (Sandbox Code Playgroud)