I am fairly new to python development and I am not sure what will be the best way to inject mocks into a function for unit testing.
I have a function which looks like:
import exampleModule
def func():
ls = createList()
exampleModule.send(ls)
In the above code I want to mock exampleModule.send method.
Should I pass the method as argument to the function? Like:
def func(invokeMethod):
ls = createList()
invokeMethod(ls)
And in unit test I can pass the mock. But I do not want the caller to specify the invocation method.
What is the right way of doing it?
You can use mock library by Michael Foord, which is part Python 3. It makes this kind of mocking very convenient. One way of doing it would be:
Here we use it as a context manager. But you ca also use
patchas a decorator. But there are more ways of usingmockand it will probably meet all your needs in mocking/stubbing.