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.
$ pip install pocketmock
Everything you need to know:
- Pocketmock mocks entire classes, not individual functions.
- There's only 1 function:
- All the methods of your mocked object will be
- Private attributes (with leading underscores) cannot be mocked, this was a design choice.
- Any instance variables found in
__init__will be set to
- 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
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
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.