Chris McKinnel
Chris McKinnel

Reputation: 15102

Avoid passing second param to every unit test using mock.patch

I'm mocking my RpcClient class for all of my unit tests like this:

import unittest2
from mock import patch

@patch('listeners.RpcClient')
class SomeTestCase(unittest2.TestCase):

    test_something(self, mock_api):
        ...

    test_something_else(self, mock_api):
        ...

For most of my tests I don't want to do any assertions using the mock object, all I want to do is patch the class so the RpcClient doesn't attempt to connect and fire requests for each of my tests (I have it hooked up to a post save event on one of my models).

Can I avoid passing in mock_api into every single one of my tests?

Upvotes: 2

Views: 88

Answers (3)

Chris McKinnel
Chris McKinnel

Reputation: 15102

I ended up doing the mocking in setUp using patcher.start():

def setUp(self):
    self.rpc_patcher = patch('listeners.RpcClient')
    self.MockClass = rpc_patcher.start()

def tearDown(self):
    self.rpc_patcher.stop()

So I don't have to decorate any of my test cases and don't have to add any extra arguments to my tests.

More info:

http://docs.python.org/dev/library/unittest.mock#patch-methods-start-and-stop

Upvotes: 2

DavidWinterbottom
DavidWinterbottom

Reputation: 6540

You could make use mock.patch as a context manager for when you call the SUT. Something like:

import unittest2
from mock import patch


class SomeTestCase(unittest2.TestCase):

    def call_sut(self, *args, **kwargs):
        with mock.patch('listeners.RpcClient'):
            # call SUT

    def test_something(self):
        self.call_sut()
        # make assertions

    def test_something_else(self):
        self.call_sut()
        # make assertions

Upvotes: 0

Leo
Leo

Reputation: 1254

Can you just set a default parameter to mock_api?

def test_something(self, mock_api=None):
    ...

def test_something_else(self, mock_api=None):

Upvotes: 0

Related Questions