pytest mock的使用

简介: 1.简单使用`return_value`返回固定的数据。2.使用`side_effect`返回可变的数据。

简单使用return_value返回固定的数据

  • 方法一,使用装饰器。

    import mock
    def add(a, b):
        return a + b
    
    
    # 使用mock的return_value参数改变add返回的数据
    @mock.patch('add', return_value=10)
    def test_add():
        print(add(1, 2))  # 10
  • 方法二,使用mock.path方法。

    import mock
    def test_add():
        with mock.patch('add', return_value=10):
            print(add(1, 2)) # 10

使用side_effect返回可变的数据

  • 当一个方法被同一个测试调用多次,而自己又不想得到同一个返回值,就轮到side_effect上场了。
  • 依次返回list里的数据。

    # 方法一
    @mock.patch('add', side_effect=[10, 20])
    def test_add():
        print(add(1, 2))  # 10
        print(add(1, 2))  # 20
    
    # 方法二
    def test_add():
        with mock.patch('add', side_effect=[10, 20]):
            print(add(1, 2))  # 10
            print(add(1, 2))  # 20
  • 根据传入的参数返回指定的数据。

    # 方法一
    @mock.patch('add', side_effect={(1, 2): 10, (2, 3): 20})
    def test_add():
        print(add(2, 3))  # 20
        print(add(1, 2))  # 10
    
    # 方法二
    def test_add():
        with mock.patch('add', side_effect={(1, 2): 10, (2, 3): 20}):
            print(add(2, 3))  # 20
            print(add(1, 2))  # 10
相关文章
33-pytest-内置fixture之pytestconfig使用
33-pytest-内置fixture之pytestconfig使用
|
8月前
|
测试技术
Pytest-插件介绍与使用
Pytest-插件介绍与使用
38 1
|
8月前
|
测试技术 Python
pytest--fixture
pytest--fixture
|
11月前
|
测试技术
pytest conftest.py和fixture的配合使用
pytest conftest.py和fixture的配合使用
|
自然语言处理 Java 测试技术
pytest学习和使用21-测试报告插件allure-pytest如何使用?
pytest学习和使用21-测试报告插件allure-pytest如何使用?
120 0
pytest学习和使用21-测试报告插件allure-pytest如何使用?
|
测试技术
pytest学习和使用12-Unittest和Pytest参数化详解
pytest学习和使用12-Unittest和Pytest参数化详解
61 0
|
测试技术 Python
pytest学习和使用6-fixture如何使用?
pytest学习和使用6-fixture如何使用?
83 0
|
测试技术
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
68 0
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
【pytest官方文档】解读fixtures - 3. fixtures调用别的fixtures、以及fixture的复用性
【pytest官方文档】解读fixtures - 3. fixtures调用别的fixtures、以及fixture的复用性
【pytest官方文档】解读fixtures - 2. fixtures的调用方式
【pytest官方文档】解读fixtures - 2. fixtures的调用方式