如何为 python 单元测试提供模拟类方法? [英] How to supply a mock class method for python unit test?

查看:26
本文介绍了如何为 python 单元测试提供模拟类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的课程.

class SomeProductionProcess(CustomCachedSingleTon):
    
    @classmethod
    def loaddata(cls):
        """
        Uses an iterator over a large file in Production for the Data pipeline.
        """
        pass

现在在测试时,我想更改 loaddata() 方法中的逻辑.这将是一个不处理大数据的简单自定义逻辑.

Now at test time I want to change the logic inside the loaddata() method. It would be a simple custom logic that doesn't process large data.

我们如何使用 Python Mock UnitTest 框架在测试时提供 loaddata() 的自定义实现?

How do we supply custom implementation of loaddata() at testtime using Python Mock UnitTest framework?

推荐答案

这是一个使用mock的简单方法

Here is a simple way to do it using mock

import mock


def new_loaddata(cls, *args, **kwargs):
    # Your custom testing override
    return 1


def test_SomeProductionProcess():
    with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
        obj = SomeProductionProcess()
        obj.loaddata()  # This will call your mock method

如果可以的话,我建议使用 pytest 而不是 unittest 模块.它使您的测试代码更加简洁,并减少了您使用 unittest.TestCase 样式测试获得的大量样板.

I'd recommend using pytest instead of the unittest module if you're able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase-style tests.

这篇关于如何为 python 单元测试提供模拟类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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