Automated Test

2023. 4. 18. 16:33Django

A piece of code which makes sure that another piece of code is working correctly under a certain condition.

 

To write an automated test in Django, you typically define a test case class that extends the

django.test.TestCase

class. You then write methods in your test case class that define the tests you want to run.

 

This is an example code :

 

from django.test import TestCase

from django.urls import reverse

 

from myapp.models import Item

 

class ItemListViewTestCase(TestCase):

def setUp(self):

# create some sample data

Item.objects.create(name='Item 1')

Item.objects.create(name='Item 2')

 

def test_item_list_view(self):

# make a request to the view

response = self.client.get(reverse('item_list'))

 

# assert that the response contains the expected data

self.assertContains(response, 'Item 1')

self.assertContains(response, 'Item 2')

 

In this example, we've defined a test case that tests a view called item_list, which should display a list of Item objects. We've created some sample Item objects in the setUp method, and then we've defined a test method called test_item_list_view that makes a request to the view using the Django test client and asserts that the response contains the expected data.