pytest--1--pytest-mock常用的方法

1. mocker.patch

mocker.patch 是最常用的方法,用于替换指定的对象或方法。它可以用于模拟函数、方法、类或模块。

语法
python 复制代码
mocker.patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
示例
python 复制代码
import pytest
from my_module import greet_user

def test_greet_user(mocker):
    # 模拟 my_module.get_greeting 函数
    mock_get_greeting = mocker.patch('my_module.get_greeting', return_value="Hi, John Doe!")
    
    result = greet_user("John Doe")
    assert result == "Hi, John Doe!"
    mock_get_greeting.assert_called_once_with("John Doe")

2. mocker.patch.object

mocker.patch.object 用于替换对象上的特定方法或属性。

语法
python 复制代码
mocker.patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
示例
python 复制代码
import pytest
from my_module import User, greet_user

def test_greet_user(mocker):
    # 模拟 User 类的 get_name 方法
    mock_get_name = mocker.patch.object(User, 'get_name', return_value="John Doe")
    
    user = User()
    result = greet_user(user)
    assert result == "Hi, John Doe!"
    mock_get_name.assert_called_once()

3. mocker.patch.dict

mocker.patch.dict 用于临时修改字典,通常用于修改环境变量或配置字典。

语法
python 复制代码
mocker.patch.dict(in_dict, values=(), clear=False, **kwargs)
示例
python 复制代码
import pytest
import os

def test_environment_variable(mocker):
    # 模拟环境变量
    mocker.patch.dict('os.environ', {'MY_VAR': 'value'})
    
    assert os.environ['MY_VAR'] == 'value'

4. mocker.spy

mocker.spy 用于创建一个 spy,它会记录方法的调用,但不会改变方法的行为。

语法
python 复制代码
mocker.spy(target, method)
示例
python 复制代码
import pytest
from my_module import User

def test_user_get_name(mocker):
    user = User(name="John Doe")
    
    # 创建一个 spy
    spy_get_name = mocker.spy(user, 'get_name')
    
    result = user.get_name()
    assert result == "John Doe"
    spy_get_name.assert_called_once()

5. mocker.stub

mocker.stub 用于创建一个没有预定义行为的模拟对象,通常用于测试回调函数。

语法
python 复制代码
mocker.stub()
示例
python 复制代码
import pytest

def test_callback(mocker):
    callback = mocker.stub()
    
    # 调用回调函数
    callback("Hello, World!")
    
    callback.assert_called_once_with("Hello, World!")

6. mocker.MagicMock

mocker.MagicMock 是一个更强大的模拟对象,可以模拟任何对象,并提供丰富的断言方法。

语法
python 复制代码
mocker.MagicMock(*args, **kwargs)
示例
python 复制代码
import pytest

def test_magic_mock(mocker):
    mock_obj = mocker.MagicMock()
    
    mock_obj.method.return_value = "Hello, World!"
    
    result = mock_obj.method()
    assert result == "Hello, World!"
    mock_obj.method.assert_called_once()

7. mocker.AsyncMock

mocker.AsyncMock 用于模拟异步函数或方法。

语法
python 复制代码
mocker.AsyncMock(*args, **kwargs)
示例
python 复制代码
import pytest
import asyncio

async def async_function():
    return "Hello, World!"

def test_async_function(mocker):
    mock_async_function = mocker.AsyncMock(return_value="Hello, World!")
    
    result = asyncio.run(mock_async_function())
    assert result == "Hello, World!"
    mock_async_function.assert_called_once()
相关推荐
chao_78910 小时前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
别在内卷了2 天前
测试学习之——Pytest Day2
服务器·学习·pytest
chao_7892 天前
pytest 实战演练【pytest】
自动化测试·单元测试·自动化·pytest
qq_513728043 天前
为什么选择 pytest 而不是 unittest
pytest
思则变3 天前
[Pytest][Part 5]单条测试和用例集测试
pytest
杨梅树5 天前
pytest中mark的使用
pytest
测试开发技术7 天前
如何在 Pytest 中调用其他用例返回的接口参数?
面试·自动化·pytest·接口·接口测试·api测试
思则变8 天前
[Pytest][Part 4]多种测试运行方式
pytest
程序员三藏8 天前
如何使用Pytest进行测试?
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest