0

It seems so easy, but I can't get the following to work. I was looking for answers in the following posts, but although related, do not cover this exact case.

I have the following class under test:

class A:
    def __init__(self, x, y):
        self.api_service = APIService(x, y)
    def my_method():
        pass

In the test case, I want to test my_method, and want to mock APIService, which is not used at all anyway in my_method. What should I mock/patch?

Things that did not work:

@patch('path.to.APIService')
class APITestCase(TestCase):
    def test_that_my_method_works(self, _):
        a = A(1, 2)
        a.my_method
        # Still calls real APIService

@patch.object(APIService, '__init__', return_value=Mock())
class APITestCase(TestCase):
    def test_that_my_method_works(self, _):
        a = A(1, 2)
        a.my_method
        # TypeError: __init__() should return None, not 'Mock'


@patch.object(APIService, '__init__', return_value=None)
class APITestCase(TestCase):
    def test_that_my_method_works(self, _):
        a = A(1, 2)
        a.my_method
        # Still calls real APIService
physicalattraction
  • 6,485
  • 10
  • 63
  • 122
  • 1
    You need to mock the `APIService` class with respect to *where you are testing*. So your first example should actually be something like `path.to.A.APIService`. You want to mock the APIService that is being used where you are testing class A. – idjaw Aug 07 '17 at 18:16
  • Read the [where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch) doc. – idjaw Aug 07 '17 at 18:17
  • 1
    Thanks! I did read that section, but didn't understand it (nor realize that it was relevant) until you pointed this out to me. – physicalattraction Aug 07 '17 at 18:21

0 Answers0