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()
相关推荐
真智AI7 小时前
用 LLM 辅助生成可跑的 Python 单元测试:pytest + coverage 覆盖率报告(含运行指令与排坑)
python·单元测试·pytest
Warren9817 小时前
Allure 常用装饰器:实战用法 + 最佳实践(接口自动化)
运维·服务器·git·python·单元测试·自动化·pytest
Warren982 天前
Pytest Fixture 到底该用 return 还是 yield?
数据库·oracle·面试·职场和发展·单元测试·pytest·pyqt
Warren983 天前
Pytest Fixture 作用域详解:Function、Class、Module、Session 怎么选
面试·职场和发展·单元测试·pytest·pip·模块测试·jira
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 44--将自动化测试结果自动推送至钉钉工作群聊
前端·python·测试工具·ui·pytest
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 45--生成项目需要的requirements.txt依赖文件
python·学习·测试工具·pytest
月明长歌4 天前
全栈测试修炼指南:从接口策略到 Python+Pytest+Allure 企业级架构
python·架构·pytest
一晌小贪欢4 天前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
我送炭你添花5 天前
Pelco KBD300A 模拟器:20.搭建pytest集成测试基础框架 + 模拟器闭环测试
python·集成测试·pytest
我送炭你添花6 天前
Pelco KBD300A 模拟器:18. 按依赖顺序 + 复杂度由低到高逐步推进pytest单元测试
python·单元测试·log4j·pytest