Reputation: 155
I am trying to do some unit testing using the mock library in Python. I have the following code:
def a():
print 'a'
def b():
print 'b'
if some condition
a()
How do I assert that a call for b
has been made when a mock call to b
has been made? I have tried the following code, but it failed:
mymock=Mock()
mymock.b()
assertTrue(a.__call__ in mymock.mock_calls)
For some reason, I think that the mymock.b()
has nothing to do with the method b()
. What can be done for this?
Upvotes: 5
Views: 8028
Reputation: 2211
If you patch a
, you can ensure it was called like so:
with mock.patch('__main__.a') as fake_a:
b()
fake_a.assert_called_with()
If your method is in a different module:
import mymodule
with mock.patch('mymodule.a') as fake_a:
mymodule.b()
fake_a.assert_called_with()
Upvotes: 7
Reputation: 14116
Somehow, I think that the mymock.b() has nothing to do with the method b() What can be done for this?
You're right. When you mock an object, you're implying that you don't care about what your mock does behind the scenes. If you wanted to make sure that a
was called from b
, you would want to patch a
in b
.
>>> from mock import patch
>>> with patch('__main__.a') as patch_a:
... b()
... patch_a.assert_called_with()
So, the moral of the story is, mock or patch over the object that you want to measure without actually calling, not the object whose implementation you care about. In this case you care about b
and want to find out how it uses a
. Since we don't care what a
does, only that it is being called, we can patch over it.
Additionally, if you want more detail about the calls to a, instead of assert_called_with
you can analyze all of the calls made by accessing the patches mock_calls
attribute. In this case it would be patch_a.mock_calls
.
Upvotes: 3