Reputation: 4937
I am struggling to wrap my head around the unittest.mock docs and the many examples on SO.
I have a class with a method:
my_class.py
import requests
class MyClass:
def do_stuff(do_it=True):
if do_it:
requests.get('https://someapi.com')
And I want a unit test that checks that do_stuff
tries to call the api using unittest.mock
I have a test (very simplified):
test_my_class.py
from django.test import TestCase
class TestMyClass(TestCase)
def test_do_stuff_uses_api(self):
MyClass().do_stuff()
# How to assert that requests.get() method was called once?
Upvotes: 1
Views: 1232
Reputation: 1846
Checkout the package requests_mock
https://requests-mock.readthedocs.io/en/latest/history.html#called
from django.test import TestCase
import requests_mock
class TestMyClass(TestCase)
def test_do_stuff_uses_api(self):
with requests_mock.mock() as m:
m.get('https://someapi.com', json={....})
MyClass().do_stuff()
history = m.request_history
self.assertEqual(len(history), 1, "Should have been called once")
Upvotes: 2