使用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
。