声明有关模拟Python类实例的内容

时间:2018-06-23 02:35:30

标签: python mocking

假设我有mock_class.py:

class SomeClass:
    def __init__(self, value):
        self.value = value

    def print_value(self):
        print(f'my value is: {self.value}')


def fubar(values):
    for value in values:
        some_class = SomeClass(value)
        some_class.print_value()

和test_mock_class.py:

from unittest import mock

import mock_class


@mock.patch('mock_class.SomeClass')
def test_fubar(mock_some_class):
    mock_class.fubar(['a', 'b'])
    assert mock_some_class.call_args_list == [
        mock.call('a'),
        mock.call('b'),
    ]

是否可以断言在每个实例上都调用了print_value

1 个答案:

答案 0 :(得分:0)

是的,您可以从该函数返回断言表达式:

def print_value(self):
    print(f'my value is: {self.value}')
    return True

然后在您的模拟类中断言:

def fubar(values):
    for value in values:
        some_class = SomeClass(value)
        assert some_class.print_value()