Python 父类中使用的模拟对象

Python 父类中使用的模拟对象,python,unit-testing,mocking,python-unittest,magicmock,Python,Unit Testing,Mocking,Python Unittest,Magicmock,我在不同的包中有两个类,其中一个继承自另一个。我想考一下儿童班 那么,如何模拟父类中使用的外部对象呢? 现在我搞不清楚它们位于哪个命名空间中。要模拟在父模块中导入和使用的任何内容,需要在父模块中模拟它 class A: def foo(self): # Make some network call or something class B(A): def bar(self): self.foo() ... class BTe

我在不同的包中有两个类,其中一个继承自另一个。我想考一下儿童班

那么,如何模拟父类中使用的外部对象呢?
现在我搞不清楚它们位于哪个命名空间中。

要模拟在父模块中导入和使用的任何内容,需要在父模块中模拟它

class A:
    def foo(self):
        # Make some network call or something


class B(A):
    def bar(self):
        self.foo()
        ...


class BTestCase(TestCase):
    def setUp(self):
        self.unit = B()

    def test_bar(self):
         with mock.patch.object(self.unit, 'foo') as mock_foo:
             mock_foo.return_value = ...
             result = self.unit.bar()
             self.assertTrue(mock_foo.called)
             ...
a/a.py

import subprocess

class A(object):
    def __init__(self):
        print(subprocess.call(['uname']))
b/b.py

from a.a import A

class B(A):
    def __init__(self):
        super(B, self).__init__()
在你的单元测试中

from b.b import B

from unittest.mock import patch

with patch('a.a.subprocess.call', return_value='ABC'):
    B()

ABC

我给你的答案加了+1,因为它暗示了mock.patch.object的用法,我以前不知道,但是这个解决方案的问题是,如果你需要模拟在uu init_u_u中使用的东西,它将不起作用。我在下面添加了解决方案