5

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?

0

1 Answer 1

8

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)
2
  • what about the constructor? if I mock the class
    – SparK
    Sep 12, 2022 at 21:02
  • Why was this accepted, it does not answer the question.
    – MikeF
    Apr 19 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.