I am trying to sub out a call to check a users full name. I have written the below method using mock to do this.
def test_UserDisplayName(self):
appModel = Mock()
eval = appModel.eval.return_value
eval.userDisplayName.return_value = 'JohnDoe'
self._SummaryModel.AppModel = appModel
actual = self._SummaryModel.UserDisplayName()
self.assertEqual(actual, 'JohnDoe')
This is the method it is calling.
def UserDisplayName(self):
return self.AppModel().eval().userDisplayName()
If I attached debugger to the above line and the run it in the shell it works
[PAUSED] >>> self.AppModel().eval().userDisplayName()
'JohnDoe'
[PAUSED] >>>
But when the run the test case for it fails as it I am getting the address back rather than the value.
======================================================================
FAIL: test_UserDisplayName (unittests.model.SummaryModelTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/unittests/summary_model.py", line 112, in test_UserDisplayName
self.assertEqual(actual, 'JohnDoe')
AssertionError: <Mock name='mock.userDisplayName()' id='233406864'> != 'JohnDoe'
----------------------------------------------------------------------
Ran 1 test in 0.010s
FAILED: (failures=1)
What am I doing wrong?
Your code calls AppModel
as well, so you need to adjust the other references for that:
eval = appModel.return_value.eval.return_value
Demo:
>>> from unittest.mock import Mock
>>> appModel = Mock()
>>> eval = appModel.return_value.eval.return_value
>>> eval.userDisplayName.return_value = 'JohnDoe'
>>> appModel().eval().userDisplayName()
'JohnDoe'
However, your <Mock name='mock.userDisplayName()' id='233406864'>
object shows a name of mock.userDisplayName()
which suggests that the return value was produced by using self.AppModel.userDisplayName()
directly instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.