python单元测试--mock

使用mock,可以将某个函数所依赖的对象或者变量mock掉,从而降低测试条件的负责度。如下所示:

def test():
    return 1

from unittest.mock import MagicMock
test = MagicMock(return_value=2)
print(test())  # 2

上述是mock对象的简单使用方法,通过实例化一个Mock对象从而模拟掉原始函数的返回值,高级一些的用法就是通过mock.patch装饰器,装饰在类或者函数上进行模拟测试,如下在test.py文件中有两个类:

# test.py为文件
class ProductionClass1:
    def __init__(self) -> None:
        pass

    def pro1_method(self) -> int:
        return 1


class ProductionClass2:
    def __init__(self) -> None:
        pass

    def test(self) -> str:
        if ProductionClass1().pro1_method() == "hello":
            return "success"

测试用例设计如下:

from unittest.mock import patch
from unittest import TestCase
import unittest

import test


class TestDemo(TestCase):
    """测试样例"""

    @patch('test.ProductionClass1')
    def test_01(self, mock_class):
        obj1 = mock_class.return_value
        obj1.pro1_method.return_value = "hello"
        print(obj1.pro1_method())                         # hello
        print(mock_class().pro1_method())                 # hello
        print(test.ProductionClass1().pro1_method())      # hello
        print(test.ProductionClass2().test())             # success


if __name__ == "__main__":
    unittest.main()

以上测试用例说明,通过patch装饰器模拟了test.ProductionClass1这个类,在test_01中使用mock_class模拟test.ProductionClass1。首先通过mock_class.return_value获取类实例(如果模拟的是函数,则不需要这一步),然后通过obj1.pro1_method.return_value设置方法的返回值,并进行测试。测试结果说明无论是通过mock_class还是test.ProductionClass1还是obj1执行方法,获取到的结果都是设置的值,并且在另一个类中调用模拟类的方法,也能成功获取到设置的return_value

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容