Python模拟-检查是否在模拟对象中调用了方法

时间:2020-08-06 19:14:54

标签: python mocking python-unittest

我有一段看起来像这样的代码:

# file1.py
from module import Object

def method():
    o = Object("param1")
    o.do_something("param2")

我的单元测试如下:

@patch("file1.Object")
class TestFile(unittest.TestCase):
    def test_call(self, obj):
        ...

我可以在单元测试中进行obj.assert_called_with()来验证是否使用某些参数调用了构造函数。是否可以验证是否使用某些参数调用了obj.do_something?我的本能不是,因为Mock已完全封装在Object中,但我希望还有其他方法。

2 个答案:

答案 0 :(得分:2)

您可以执行此操作,因为参数已传递给模拟对象。
这应该起作用:

@patch("file1.Object")
class TestFile:
    def test_call(self, obj):
        method()
        obj.assert_called_once_with("param1")
        obj.return_value.do_something.assert_called_once_with("param2")

obj.return_valueObject实例(它是具有MagickMock规范的Object对象),而do_something是该对象中的另一个模拟,即用给定的参数调用。

只要您只是将参数传递给模拟对象,模拟就会记录下来并可以对其进行检查。您没有的是实际函数调用的任何副作用-因此,如果原始的do_something将调用另一个函数,则无法检查。

编辑: 我没有正确阅读其他答案-它也正确回答了问题。所以这更多是对该答案的修正...

答案 1 :(得分:0)

模拟对象时,它还将模拟对象内部的方法。因此,您可以查看是否已使用某些参数obj.do_something调用了obj.do_something.assert_called_with()

有关单元测试模拟的更多信息,请参见python库Wiki https://docs.python.org/3/library/unittest.mock.html

该维基资源中存在一个关于您要问的完美示例:

>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_with

关于,我看到您已将补丁放置在对象上,尝试将其放置在函数上,例如:

class TestFile(unittest.TestCase):
    @patch("file1.Object")
    def test_call(self, obj):
        ...