Python mockito - Mocking a class which is being instantiated from the testable function
It is quite simple if you know the trick.
Creating an object in Python is very much like a function call to the class object. UserCompanyRateLimitValidation
is 'invoking' UserAdapter(user_public_key)
. You want to stub the return value of that 'call' to return UserAdapter_mock
.
You can stub this like you would stub a function in a module. The line you're missing is:
when(module_declaring_UserAdapter)\
.UserAdapter(self.user_public_key)\
.thenReturn(UserAdapter_mock)
After that, calling module_declaring_UserAdapter.UserAdapter(self.user_public_key)
will return UserAdapter_mock
.
Here's the link to the section in the manual: https://code.google.com/p/mockito-python/wiki/Stubbing#Modules
You have to be careful to choose the right module_declaring_UserAdapter
, due to the way the from ... import ...
statement works. From your code, I'd say you have to pick the module in which UserCompanyRateLimitValidation
is declared.