【问题标题】:How to mock.patch a dependancy in Python?如何在 Python 中对依赖项进行猴子补丁?
【发布时间】:2017-12-05 19:22:05
【问题描述】:

模拟一个依赖的方法对我不起作用。当我需要测试的方法调用它的依赖方法时,调用的是真正的方法,而不是它的mock版本。

我确实有以下文件:

myLibrary.py

from src.myOtherLibrary import myOtherLibrary
class myLibrary():
    def __init__():
        self.myVar = myOtherLibrary() #dependancy

    def my_method():
        method1 = self.method1()

        externalMethod2 self.myVar.method2() #method2 called from the external class myOtherLibrary

        return method1 + externalMethod2

    def method1():
        return "method1 from myLibrary..."

src/myOtherLibrary.py

class myOtherLibrary():
    def method2():
        return "method2 from myOtherLibrary..."

最后是单元测试:

TestMyLibrary.py

import unittest
import mock
from myLibrary import myLibrary
from src.myOtherLibrary import myOtherLibrary
class TestMyLibrary(unittest.TestCase):
    @mock.patch('myLibrary.myLibrary.method1') #mocking this works because it's a sibling method from my_method() to test
    @mock.patch('src.myOtherLibrary.myOtherLibrary.method2') #this does not work because it's an external class from myLibrary
    def test_my_method(my_method1_to_mock, my_method2_to_mock):
        my_method1_to_mock.return_value = "something_to_return.."
        my_method2_to_mock.return_value = "something_else_to_return.."

        myLibraryVar = myLibrary()
        result = myLibraryVar.my_method()
        print result #I would expect to see this: "something_to_return..something_else_to_return.."
                     #But it actually prints this: "something_to_return..method2 from myOtherLibrary..."
                     #So mocking is not working for method2

        self.assertEqual('something_to_return..something_else_to_return..', result)

if __name__ == '__main__':
    unittest.main()

也许值得一提的是 myLibrary.py 和 TestMyLibrary.py 位于同一个文件夹中,但 myOtherLibrary.py 位于不同的文件夹级别。

我希望你能帮我找到我在这里缺少的东西。

任何建议都将不胜感激。 谢谢。

【问题讨论】:

    标签: python-2.7 mocking python-unittest python-mock patch


    【解决方案1】:

    你不能patch 那样,因为你试图模拟的方法是类方法而不是函数。所以你需要使用patch.object

    @mock.patch.object(myLibrary, 'method1') 
    @mock.patch.object(myOtherLibrary, 'method2') 
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2013-12-28
      • 2015-08-02
      • 2011-04-15
      • 1970-01-01
      相关资源
      最近更新 更多