I need to test that my class's constructor calls some method
class ProductionClass:
def __init__(self):
self.something(1, 2, 3)
def method(self):
self.something(1, 2, 3)
def something(self, a, b, c):
pass
This class is from 'unittest.mock — getting started'. As written there I can make sure that 'method' called 'something' as follows.
real = ProductionClass()
real.something = MagicMock()
real.method()
real.something.assert_called_once_with(1, 2, 3)
But how to test the same for constructor?
You can make use of patch (check the docs for it https://docs.python.org/dev/library/unittest.mock.html) and assert that after creating a new instance of the object, the something
method was called once and called with the parameters required. For instance, in your example it would be something like this:
from unittest.mock import MagicMock, patch
from your_module import ProductionClass
@patch('your_module.ProductionClass.something')
def test_constructor(something_mock):
real = ProductionClass()
assert something_mock.call_count == 1
assert something_mock.called_with(1,2,3)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With