今天在编写一些测试时,我遇到了一个令人困惑的行为:
Foo
类定义:
class Foo:
def bar(self, attrs):
self._baz(attrs)
attrs.pop('key')
def _baz(self, attrs):
pass
Foo
班级考试:
from unittest import TestCase, mock
class FooTestCase(TestCase):
def test_bar(self):
foo = Foo()
attrs = {'key': 'value'}
with mock.patch.object(foo, '_baz') as _baz_mock:
# Copying `attrs` so that `foo.bar()` won't mutate it.
foo.bar({**attrs})
# Test fails here since `_baz_mock` gets called with `{}` (not sure why).
_baz_mock.assert_called_once_with(attrs)
我希望_baz_mock.assert_called_once_with(attrs)
成功通过,因为Foo.bar()
在调用attrs.pop('key')
后执行self._baz(attrs)
,但是it fails使用以下{{} {1}}:
AssertionError
有人可以解释一下这里发生了什么以及为什么Expected call: _baz({'key': 'value'})
Actual call: _baz({})
被_baz_mock
调用了?