【问题标题】:Mock method in test file from different directory python来自不同目录python的测试文件中的模拟方法
【发布时间】:2018-08-29 00:24:59
【问题描述】:

我试图模拟一个方法并遇到mock 实际上覆盖它的问题。

app/tests/test_file.py

@mock.patch('app.method', return_value='foo')
def test(self, thing):
    ...
    do some stuff with app/main/server.py 
    and get its response, assert a few values
    ...
    assert 'foo' is in return value of some stuff

正在被模拟的方法正在被 server.py 正在调用的另一个文件调用。

  • app/main/server.py
  • app/main/route.py
  • app/main/thing.py

这是python 2.7,每个包都有一个init文件。父文件夹 (app) 包含每个类和方法的导入。我试过app.method 没有问题,但不起作用。我试过thing.method,抛出一个错误。我试过 app.main.thing.method 什么都没做。

我在同一个测试套件中成功地模拟了一个对象及其方法之一,但该对象是在 server.py 文件中直接创建和使用的。我想知道是不是因为被调用的方法太远了。模拟对我来说非常神奇,尤其是在 Python 中。

【问题讨论】:

  • 它不在一个类中,在我上面的示例中它在thing.py 模块中。

标签: python python-2.7 unit-testing mocking


【解决方案1】:

经过更多的挖掘终于弄明白了,将把它留给其他有问题的人(特别是因为它不容易被谷歌搜索)。

正如@Gang 指定的完整路径应该可以工作,但是模块需要是调用方法的模块,而不是它所在的模块,as this person points out.。使用@Gang 示例:

@mock.patch('app.main.route.method')
def test(self, mock_method):
    mock_method.return_value = 'foo'
    # call and assert

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-08
    • 2018-07-17
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多