Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing constructor using mock

Tags:

python

mocking

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?

like image 916
ArmanHunanyan Avatar asked Mar 09 '23 16:03

ArmanHunanyan


1 Answers

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)
like image 191
Enrique Saez Avatar answered Mar 25 '23 05:03

Enrique Saez