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

时间:2019-12-04 14:49:54

标签: python python-2.7 mocking python-unittest

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

例如a.py是:

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

ToBeMocked()将在调用后被调用

from a import A

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

1 个答案:

答案 0 :(得分:0)

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

例如

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/stackoverflow/59178731/a.py            4      0   100%
src/stackoverflow/59178731/arg.py          2      1    50%   2
src/stackoverflow/59178731/test_a.py      11      0   100%
--------------------------------------------------------------------
TOTAL                                     17      1    94%