pocketmock
Sometimes it's a pain to create mock objects. Here's ~30 lines of code to simplify the process.
Note: this currently only works with python3. Giving it backwards compatibility should be very easy, but I haven't done it yet.
Installation
$ pip install pocketmock
Usage
Everything you need to know:
- Pocketmock mocks entire classes, not individual functions.
- There's only 1 function:
pocketmock.create_mock_object
. - All the methods of your mocked object will be
unittest.mock.MagicMock
instances. - Private attributes (with leading underscores) cannot be mocked, this was a design choice.
- Any instance variables found in
__init__
will be set toNone
. - No code in your mocked class will ever be called. Period.
Here's an example where I mock out a websocket connection in order to test a CoolMessageSender
.
Production code:
class CoolMessageSender:
def __init__(self, websocket):
self.websocket = websocket
def send_cool_message(self, message):
message = "COOL: " + message
self.websocket.send(message)
class Websocket:
"""You can pretend this class is implemented..."""
def send(message): pass
Test code:
from unittest import TestCase
from pocketmock import create_mock_object
class CoolMessageSenderTest(TestCase):
def test_send_cool_message(self):
mock_websocket = create_mock_object(Websocket)
cool_message_sender = CoolMessageSender(mock_websocket)
cool_message_sender.send("Hello!")
mock_websocket.send.assert_called_with("COOL: Hello!")
To see all the assertions you can do with the mocked methods, check the MagicMock documentation.
You can use any testing framework you like, I've chosen unittest
for this example because it's common.