Skip to content

Tutorial to Write Tests For Django REST API endpoints

Mücahit Erdoğan Ünlü edited this page Apr 27, 2024 · 2 revisions

How to write tests for Django REST API endpoints?

Unit Testing

Testing Views

  1. Create a folder named "tests" in your django app.
  2. Create an empty python file named "__init__.py" inside "tests" folder.
  3. Create a file to write tests. File name should start with "test" name.
    • Inside the file
      • from rest_framework.test import APITestCase
      • Create a class with name starting with "Test" inheriting APITestCase
      • In the urls.py file, give names as parameters in addition to paths and their views.
      • from django.urls import reverse to reverse the given names and obtain the absolute paths.
      • Create a method that has "test" in the beginning of its name.
      • Create a mock data to be sent using response = self.client.post(self.your_url_name, self.your_data, format='json')
      • You can see the response data using response.data or status using response.status_code
      • Use assertEqual to validate the test. Example: self.assertEqual(response.status_code, 200) for a request that is supposed to be successful.
      • You can create multiple test methods. They are run independent of each other.
      • run python manage.py test to run all of the tests.
      • Tests do not interact with your actual database. Example:
from rest_framework.test import APITestCase
from django.urls import reverse

class TestView(APITestCase):

    def test_add_user(self):
        self.add_user_url = reverse('add_user')
        self.user_data = {
            'username': "rider",
            'email': "ali@email.com",
            'name': "ali",
            "surname": "yilmaz"
        }
        response = self.client.post(self.add_user_url, self.user_data, format='json')
        self.assertEqual(response.status_code, 200)

Additional Notes

  • You can install faker to generate random data. Example:
from faker import Faker
user_data = {
     'username': Faker().user_name(),
     'email': Faker().email(),
     'password': Faker().password(),
}

BOUNSWE2024 - G11

Logo Turquiz App

⏳ Status

  • Implementation Phase 1
  • Design
  • Scenarios & Mockups
  • Software Requirements Specification
  • Forming the Team

🧑🏼‍💻 Team

📝 Diagrams

📆 Lab Reports

📆 Meeting Notes

📍 Milestones

📚 User Scenarios

📚 Resources

🔎 Research

🗂️ Templates

Clone this wiki locally