如何修补从python中的实例调用的方法

时间:2017-05-28 13:58:39

标签: python mocking monkeypatching magicmock

我正在尝试为我的文件 abc.py 编写单元测试版。 我无法为从类实例调用的方法设置返回值。

这是我的档案:

abc.py

class ABC(object):
    def __init__(self):
        pass

    def fetch_id(self):
        id = # from somewhere
        return id

def main():
    module = someRandomClass()
    client = ABC()
    account_id = client.fetch_id()
    module.save(account_id=account_id)

if __name__ == '__main__':
    main()

这是测试文件

test.py

import mock
import abc

@mock.patch('abc.ABC')
@mock.patch('someRandomClass')
def test_all(module, mock_abc):
    abc.main()
    module.assert_called_with()

    client = mock_abc.return_value
    mock_abc.assert_called_with()

    client.fetch_id.return_value = '12345667'
    module.save.assert_called_with(account_id='12345667')

收到以下错误:

AssertionError: Expected call: save(account_id='12345667')
Actual call: save(account_id=<MagicMock name='ABC().fetch_id()' id='4507253008'>)

1 个答案:

答案 0 :(得分:0)

在调用abc.main()之前,需要设置函数的返回值。

import mock
import abc

@mock.patch('abc.ABC')
@mock.patch('someRandomClass')
def test_all(module, mock_abc):
    client = mock_abc.return_value
    client.fetch_id.return_value = '12345667'
    abc.main()
    module.assert_called_with()

    mock_abc.assert_called_with()

    module.save.assert_called_with(account_id='12345667')