Skip to content Skip to sidebar Skip to footer

Mock A Class With Tedious __init__

I have a class that actually connects to a service and does authentication and stuff, but all of this is well tested somewhere else in my code, I just want to mock in the following

Solution 1:

I think that is a typical use case for mock.patch. Take care that patch decorator need the full path of the module where the main module become __main__

from mock import patch, Mock
from abmodule import A,  B #Where A and B are@patch("abmodule.B")deftest_A(bmock):
    # Set B costructor to return a Mock object
    bmock.return_value = Mock()
    bmock.upload.return_value='Hi'
    a = A()
    a.send()
    #Check if upload was called!
    bmock.return_value.upload.assert_called_with()

After that you could use use again the original B in the other part of the code: the patched version live just in scope of the function.

Solution 2:

You need to patch the actual class with the mocked B. py.test provides the monkeypatch fixture for this:

import unittest.mock
import mut  # module under test, where A and B are defined.

def test_A(monkeypatch):
    b = unitest.mock.Mock()
    b.upload.return_value = 'Hi'
    monkeypatch.setattr(mut, 'B', b)
    a = mut.A()
    a.send()

Post a Comment for "Mock A Class With Tedious __init__"