父类中使用的模拟对象

时间:2018-04-26 09:31:08

标签: python unit-testing mocking python-unittest magicmock

我在单独的包中有两个类,其中一个继承自另一个。我想测试孩子班。

那么如何模拟父类中使用的外部对象呢? 我很困惑他们目前居住在哪个命名空间。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

A / a.py

var rand = myArray[~~(Math.random() * myArray.length)];

B / b.py

Math.Floor()

在你的unittest中

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343
相关问题