Python unittest 补丁模拟实体类 [英] Python unittest patch mock entier class

查看:52
本文介绍了Python unittest 补丁模拟实体类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单元测试中修补一个类.

I have a class that I want to patch in my unittests.

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

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

Now I created another class to patch it with, so the code for patching it is like

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()    

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

This works exactly as I want it to and I can return whatever responses required for my unittests.

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

Now this issue is when I want to verify that a method is called with the right parameters in the unittests. I tried

mock_instance.method_a.assert_called_once()

但它失败并出现错误 AttributeError: 'function' object has no attribute 'assert_called_once'.

But it fail with error AttributeError: 'function' object has no attribute 'assert_called_once'.

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

How can I test the method calls here?

推荐答案

我认为 wraps 在这里很有用:

I think wraps can be useful here:

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()].

这篇关于Python unittest 补丁模拟实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆