如何在Python中使用mock.patch依赖?

时间:2017-12-05 19:22:06

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

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

我有以下文件:

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位于不同的文件夹级别。

我希望你能帮助我找到我在这里失踪的东西。

任何建议都将得到很好的赞赏。 感谢。

1 个答案:

答案 0 :(得分:0)

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

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