首页 > 解决方案 > Python unittest补丁模拟实体类

问题描述

我有一个类,我想在我的单元测试中修补。

class OriginalClass():
   def method_a():
     # do something
   
   def method_b():
     # do another thing

现在我创建了另一个类来修补它,所以修补它的代码就像

class MockClass(OriginalClass):
    def method_a():
        # This will override the original method and return custom response for testing.

patcher = patch('OriginalClass', new=MockClass)
mock_instance = patcher.start()    

这完全符合我的要求,我可以返回单元测试所需的任何响应。

现在这个问题是当我想验证在单元测试中使用正确的参数调用方法时。我试过了

mock_instance.method_a.assert_called_once()

但它因错误而失败AttributeError: 'function' object has no attribute 'assert_called_once'

如何在这里测试方法调用?

标签: pythonunit-testingmockingpytestpatch

解决方案


我认为wraps在这里有用:

from unittest.mock import patch

class Person:
    name = "Bob"
    def age(self):
        return 35

class Double(Person):
    def age(self):
        return 5


with patch('__main__.Person', wraps=Double()) as mock:
    print(mock.name)  # mocks data
    print(mock.age()) # runs real methods, but still spies their calls
    mock.age.assert_not_called()

输出:

<MagicMock name='Person.name' id='139815250247536'>
5
...
raise AssertionError(msg)
AssertionError: Expected 'age' to not have been called. Called 1 times.
Calls: [call()].

推荐阅读