问题
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