如何为 python 单元测试提供模拟类方法?

2022-01-08 00:00:00 python mocking unit-testing

问题描述

假设我有这样的课程.

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.

相关文章