几天前,我开始学习使用pytest进行单元测试,并对pytest-mock插件(https://github.com/pytest-dev/pytest-mock)产生了兴趣。
我已经能够编写相当多的单元测试来测试我的代码,但现在我想测试我的代码部分如何与其他对象交互。假设我有一个类B,这是我有兴趣测试的类,它有一个方法将调用类A中的方法,并且我想断言,当类B调用类A时,该方法调用是使用预期的参数进行的。
我整理了一些示例hack (参见下面的链接)来完成工作,但正如您所看到的,这可能不是正确的做法。因此,我的问题是,如何通过使用Python mock或pytest-mock模块正确处理此问题?不是基于pytest-mock插件的答案也很受欢迎。
在下面的代码中,它是我不满意的断言,因为我更喜欢使用现有的最模拟的"assert_called_once_with(...)"-method,但我就是不能让它工作。所有信息都在mock-object中,但我不明白在这种情况下如何正确使用pytest-mock API。
def test_how_class_b_interact_with_class_a(mocker):
class A(object):
def further_process_nbr(self, nbr):
pass # don't care for the sake of this example
class B(object):
def __init__(self):
self.a = A()
def process_nbr(self, nbr):
nbr += 2 # do something fancy with number and then have it further processed by object a
return self.a.further_process_nbr(nbr)
nbr = 4
expected = 6
# Prepare
mock_a = mocker.patch.object(A, 'further_process_nbr', autospec=True)
# Exercise
B().process_nbr(nbr)
# Assert
assert mock_a.call_args_list[0].args[1] == expected # This is working, but not exactly a nice way
# mock_a.assert_called_once_with(expected) something like this is basically what I would like to do发布于 2020-01-20 20:15:27
实际上,您看到的结果是正确的,在:
assert (<a.A object at 0x000001628C6878B0>, 2) == (2,)您在元组的第一个元素中看到的是self参数,因为您模拟了类中的方法,所以它也接收self。
要使用assert_called_once_with检查这一点,可以使用mocker.ANY,它可以接受任何内容:
mock_a.assert_called_once_with(mocker.ANY, nbr)https://stackoverflow.com/questions/59819455
复制相似问题