I'm trying to spy on a class object and see if class instance method is called with right parameters.
I can't use Mock(wraps=obj_instance)
because the flow I trigger creates its own object instance.
I tried to use Mock(spec=obj_class)
as seen in below, but it doesnt work.
Any ideas on how to spy on instance methods without creating the instance beforehand?
from mock import Mock
import unittest
class CreditAPI:
def __init__(self, *args, **kwargs):
self.user = kwargs['user']
def add_credit(self, amount):
print("adding amount %s to user %s" % (amount, self.user))
def consume_credit():
credit_api = CreditAPI(user="Ali")
credit_api.add_credit(50)
class ConsumeCreditTestCase(unittest.TestCase):
def test_consume_credit(self):
m_credit_api = Mock(spec=CreditAPI)
consume_credit()
m_credit_api.__init__.assert_called_with(user="Ali") # doesnt work
m_credit_api.add_credit.assert_called_with(50) # doesnt work
if __name__ == '__main__':
unittest.main()