1

我正在尝试为我的文件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()

这是测试文件

测试.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'>)
4

1 回答 1

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')
于 2017-05-28T14:58:34.950 回答