【发布时间】:2019-07-05 15:19:03
【问题描述】:
我试图在一个函数中模拟几个函数调用,以便测试它们的行为。
我尝试了几种不同的方法,如代码所示,但 should_be_mocked 函数永远不会被模拟。我用的是python3,PyCharm,测试框架设置为pytest
test.py
from unittest import mock, TestCase
from unittest.mock import patch
from path import should_be_mocked
from other_path import flow
def test_flow(monkeypatch):
def ret_val():
return should_be_mocked("hi")
monkeypatch.setattr('path', "should_be_mocked", ret_val())
assert flow() == "hi"
def test_flow2(monkeypatch):
monkeypatch.setattr('path.should_be_mocked', lambda x: "hi")
assert flow() == "hi"
@patch('path.should_be_mocked')
def test_flow3(mocker):
mocker.return_value = "hello returned"
flow()
mocker.test.assert_called_with("hello")
class TestStuff(TestCase):
@patch('path.should_be_mocked')
def test_flow4(self, mocker):
mocker.return_value = "hello returned"
flow()
mocker.test.assert_called_with("hello")
路径
def should_be_mocked(hello):
return hello
其他路径
def flow():
# business logic here
return should_be_mocked("hello")
所有测试都失败并从真实函数返回值。我哪里做错了?
添加信息。
尝试将路径更改为 other_path 导致
E AttributeError: 'other_path' has no attribute 'should_be_mocked'
【问题讨论】:
-
你应该嘲笑
other_path.should_be_mocked而不是path.should_be_mocked。详情请见Where to patch。
标签: python mocking pytest monkeypatching