3

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?

2 Answers 2

2

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:

>>> from mock import patch
>>> import exampleModule
>>>    
>>> def func():
...     ls = []
...     exampleModule.send(ls)
... 
>>> with patch('exampleModule.send') as send:
...     func()
...     assert send.called

Here we use it as a context manager. But you ca also use patch as a decorator. But there are more ways of using mock and it will probably meet all your needs in mocking/stubbing.

Sign up to request clarification or add additional context in comments.

Comments

1

Python supports functions as first class citizens, so you can override the implementation of a method for unit testing purposes.

This approach basically shows you the way.

class Foo
   def thing_to_mock():
      really_expensive_stuff()

   def thing_to_test():
       i = 1 + 2
       thing_to_mock()
       return i

class FooTest
  def testingThingToTest():
       def mocker():
           pass
       toTest = Foo()
       toTest.thing_to_mock = mocker
       # assert here

Alternately, in Python 3.3 you can use the built-in mocking support.

1 Comment

The difference is, in my case, I am not testing a method (function in a class) but a high level function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.