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.
- Mocking an entire class
- Mocking a class: Mock() or patch()?
- Mock entire python class (where actually only a method is mocked)
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