父类中使用的模拟对象

2024-04-25 13:05:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

那么如何模拟父类中使用的外部对象呢? 我不知道他们在哪一个名称空间驻留在这一点上。你知道吗


Tags: 对象名称空间儿童父类
2条回答

要模拟在父模块中导入和使用的任何内容,您需要在父模块中模拟它。你知道吗

应付账款

import subprocess

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

双倍

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
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)
             ...

相关问题 更多 >