Reputation: 14584
I'm getting confused by using Mock in my python unittests. I've made this simplified version of my problem:
I have this dummy class and methods:
# app/project.py
class MyClass(object):
def method_a(self):
print(FetcherA)
results = FetcherA()
Which is using this class:
# app/fetch.py
class FetcherA(object):
pass
And then this test:
# app/tests/test.py
from mock import patch
from django.test import TestCase
from ..project import MyClass
class MyTestCase(TestCase):
@patch('app.fetch.FetcherA')
def test_method_a(self, test_class):
MyClass().method_a()
test_class.assert_called_once_with()
I would expect that running this test would pass and that print
statement, for debugging, would output something like <MagicMock name=...>
. Instead it prints out <class 'app.fetch.FetcherA'>
and I get:
AssertionError: Expected to be called once. Called 0 times.
Why isn't FetcherA
being patched?
Upvotes: 8
Views: 2534
Reputation: 14584
OK, fourth time through I think I understood the 'Where to patch' section of the Mock docs.
So, instead of:
@patch('app.fetch.FetcherA')
I should use:
@patch('app.project.FetcherA')
Because we're testing the code in app.project.MyClass
where FetcherA
has been imported already. So at that point FetcherA
is availably globally(?) within app.project
.
Upvotes: 19