Mock function from other module

本小妞迷上赌 提交于 2019-12-08 04:00:22

问题


I have two python files:

function.py:

def foo ():
    return 20

def func ():
    temp = foo()
    return temp

and mocking.py:

 from testing.function import *
 import unittest
 import mock
 class Testing(unittest.TestCase):

 def test_myTest(self):

     with mock.patch('function.func') as FuncMock:
         FuncMock.return_value = 'string'

         self.assertEqual('string', func())

I want to mock func, but with no positive result. I have AssertionError: 'string' != 20. What should I do to mock it correctly ? If I do mock.patch ('func') I have TypeError: Need a valid target to patch. You supplied: 'func'. If I move func to mocking.py and call foo: function.foo() it works correctly. But how to do it when I don't want to move functions from function.py to mocking.py ?


回答1:


Mocking is useful when you're calling an actual function but you want some function calls inside that function to be mocked out. In your case you're aiming to mock func and you wish to call that mocked function directly by doing func().

However that won't work because you're mocking function.func but you've imported func already into your test file. So the func() that you're calling is an actual function, it's not the same as the mocked FuncMock. Try calling FuncMock() and you'll get the result as expected.

The following should work and it gives you an idea of what can be done:

from testing.function import func
import unittest
import mock

class Testing(unittest.TestCase):

    def test_myTest(self):

        with mock.patch('testing.function.foo') as FooMock:
            FooMock.return_value = 'string'

            self.assertEqual('string', func())


来源:https://stackoverflow.com/questions/27302776/mock-function-from-other-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!