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()
相关推荐
我的xiaodoujiao2 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 24--数据驱动--参数化处理 Excel 文件 1
python·学习·测试工具·pytest
西游音月5 天前
(2)pytest+Selenium自动化测试-环境准备
selenium·测试工具·pytest
我的xiaodoujiao6 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 23--数据驱动--参数化处理 Yaml 文件
python·学习·测试工具·pytest
我的xiaodoujiao9 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
胜天半月子9 天前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
北珣.13 天前
自动化框架pytest基础
自动化·pytest
程序员杰哥14 天前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
学习3人组15 天前
Python + requests + pytest + allure + Jenkins 构建完整的接口自动化测试框架
python·jenkins·pytest
shao91851618 天前
Gradio全解14——使用Gradio构建MCP的服务器与客户端(4)——Python包命令:uv与uvx实战
pytest·uv·1024程序员节·npx·uvx·uv pip·ruff
我的xiaodoujiao19 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest