【问题标题】:Unable to mock a function call from a function call from the test function无法模拟来自测试函数的函数调用的函数调用
【发布时间】:2019-12-02 00:24:09
【问题描述】:

我遇到了测试问题,希望能得到一些帮助。

我的一位同事将我指向 unittest.mock 和 patch,它们似乎正是我所需要的,但我无法使其正常工作。

编写的问题:我有我的测试用例,它调用和测试 python 文件 (fooFile) 中的函数 (foo),它调用另一个 python 文件 (barFile) 中的另一个函数 (bar)。 bar 函数是我需要从测试文件中模拟出来的。

示例代码:

barFile.py

#homedir.lib.barFile.py

def bar(object2):
    return False

fooFile.py

#homedir.api.fooFile.py
from homedir.lib.barFile import bar

def foo(object1):
    result = bar(object1['item1'])
    if result:
        return 200
    else:
        return 400

testFooFile.py -- 没有模拟

#homedir.tests.testFooFile.py
from homedir.api.fooFile import foo

def testFoo():
    payload = {"item1": "nothing"}
    result = foo(payload)
    assert result == 200

基本上,从 testFooFile.py 文件中,我需要模拟 bar 函数并让它返回 True。我只能通过 foo 调用 bar,这就是我的问题所在。我可以很好地模拟 bar 函数,但只有当我直接从 testFile 调用它时,而不是当它被 foo 函数调用时。这与我目前所拥有的有点相似。


testFooFile.py -- 当前想法

#homedir.tests.testFooFile.py
from unittest.mock import patch
from homedir.api.fooFile import foo

@patch('homedir.lib.barFile.bar')
def testFoo(mock_bar):
    mock_bar.return_value = True

    payload = {"item1": "nothing"}
    result = foo(payload)
    assert result == 200

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    我相信你正在修补的路径应该是homedir.api.fooFile.bar。您需要修补foo() 正在使用的bar() 实例,该实例位于fooFile.py

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2021-03-30
      相关资源
      最近更新 更多