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()
相关推荐
Kingairy12 小时前
Pytest 插件:pytest_runtest_protocol
python·pytest
AIZHINAN14 小时前
Pytest 插件介绍和开发
测试工具·pytest·插件开发
灰阳阳3 天前
替身演员的艺术:pytest-mock 从入门到飙戏
自动化测试·python·pytest·unit testing·pytest-mock
年年测试6 天前
Playwright与PyTest结合指南
pytest
focksorCr6 天前
pytest 并发执行用例(基于受限的测试资源)
python·pytest
律品11 天前
pytest的前置与后置
开发语言·python·pytest
测试老哥12 天前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
丿罗小黑13 天前
Pytest项目_day20(log日志)
pytest
xt198928813 天前
pytest+yaml+allure接口自动化测试框架
自动化测试·pytest·接口自动化·框架封装
灰阳阳13 天前
接口自动化测试大全(python+pytest+allure)
python·pytest·接口自动化·allure