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()
相关推荐
天才测试猿7 小时前
Python常用自动化测试框架—Pytest详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
慌糖16 小时前
自动化接口框架搭建分享-pytest第二部分
运维·自动化·pytest
know__ledge18 小时前
Pytest+requests进行接口自动化测试6.0(Jenkins)
elasticsearch·jenkins·pytest
慌糖2 天前
自动化接口框架搭建分享-pytest
运维·自动化·pytest
Rhys..2 天前
Gerkin+Pytest(python)实现自动化(BDD)
python·自动化·pytest
啊森要自信2 天前
【 GUI自动化测试】GUI自动化测试(一) 环境安装与测试
开发语言·python·ui·单元测试·pytest
know__ledge3 天前
Pytest+requests进行接口自动化测试5.0(5种assert断言的封装 + pymysql)
服务器·开发语言·python·测试用例·pytest
摘星编程15 天前
AI 帮我写单测:pytest 覆盖率提升 40% 的协作日志
人工智能·pytest·测试驱动开发·代码覆盖率·ai协作开发
lucia_zl17 天前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试17 天前
Selenium4+Pytest自动化测试框架实战
pytest