使用 pytest.fixture 返回模拟对象的正确方法 [英] Proper way to return mocked object using pytest.fixture

查看:68
本文介绍了使用 pytest.fixture 返回模拟对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 @pytest.fixture 中设置被测目标,并在模块中的所有测试中使用它.我能够正确修补测试,但是在添加 @pytest.fixture 以返回模拟对象并在其他单元测试中调用模拟对象后,该对象开始引用回原始函数.

I'm trying to setup the target under test in @pytest.fixture and use it in all my tests in the module. I'm able to patch the test correctly, but after I add the @pytest.fixture to return the mock object and invoke the mocked object in other unit tests the object starting to refer back to the original function.

以下是我的代码.我期望单元测试中的 mocked_worker 引用返回值,但它正在调用实际的 os.getcwd 方法.

Following is the code I have. I was expecting the mocked_worker in the unit test to refer to the return value, but it is invoking the actual os.getcwd method instead.

请帮我更正代码:

import os
import pytest
from unittest.mock import patch

class Worker:
    def work_on(self):
        path = os.getcwd()
        print(f'Working on {path}')
        return path

@pytest.fixture()
def mocked_worker():
    with patch('test.test_module.os.getcwd', return_value="Testing"):
        result = Worker()
    return result

def test_work_on(mocked_worker):
    ans = mocked_worker.work_on()
    assert ans == "Testing"

推荐答案

问题是当worker返回with"语句的作用域结束使对象取其真实值时,解决方案是使用yield".

The problem is that when the worker returns the scope of "with" statement ends making the object take its real value, the solution is to use "yield".

@pytest.fixture()
def mocked_worker():
    with patch('test.test_module.os.getcwd', return_value="Testing"):
        result = Worker()
        yield result

这篇关于使用 pytest.fixture 返回模拟对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆