在方法签名中调用的模拟方法

Mocking methods that been called in method's signatures

我正在寻找一种方法来模拟因获取参数的默认值而被调用的方法。

例如a.py是:

class A():
    def __init__(self, arg=ToBeMocked())

ToBeMocked()调用后会调用:

from a import A

如何在调用 import 语句之前模拟 ToBeMocked()

在从 a 模块导入 A class 之前使用 unittest.mock.patch 修补 ToBeMocked 函数。

例如

a.py:

from arg import ToBeMocked


class A():
    def __init__(self, arg=ToBeMocked()):
        self.arg = arg

arg.py:

def ToBeMocked():
    return 'teresa teng'

test_a.py:

import unittest
from unittest import mock


class TestA(unittest.TestCase):
    @mock.patch('arg.ToBeMocked')
    def test__init__(self, mock_ToBeMocked):
        mock_ToBeMocked.return_value = 'Love Teresa Teng'
        from a import A
        a_instance = A()
        self.assertEqual(a_instance.arg, 'Love Teresa Teng')
        mock_ToBeMocked.assert_called_once()


if __name__ == '__main__':
    unittest.main()

带有覆盖率报告的单元测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Name                                   Stmts   Miss  Cover   Missing
--------------------------------------------------------------------
src/Whosebug/59178731/a.py            4      0   100%
src/Whosebug/59178731/arg.py          2      1    50%   2
src/Whosebug/59178731/test_a.py      11      0   100%
--------------------------------------------------------------------
TOTAL                                     17      1    94%