来自不同目录python的测试文件中的模拟方法

时间:2018-08-29 00:24:59

标签: python python-2.7 unit-testing mocking

我正在尝试模拟一个方法,并遇到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.method,但没有遇到问题,但是没有用。我尝试过thing.method,并抛出错误。我尝试了app.main.thing.method,但它什么也没做。

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

1 个答案:

答案 0 :(得分:0)

经过更多的挖掘,终于找到了答案,将它留给有问题的其他人(尤其是因为它不容易被Google使用)。

正如@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