简体   繁体   中英

Python's mock.patch not patching class in unittest

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?

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM