Unit Testing in Django
Introduction
It is nearly impossible to build an application that is free from bugs or works perfectly so it is important to test your web application to find these errors and work on them proactively.To find these errors testing is done .Manual testing is time-intensive and leaves room for error, so most programmers dedicate serious attention to automated testing.
Automated testing is the process in which testers use tools and scripts to automate testing efforts.Automated testing saves time and improves software quality. A proper implementation of automated testing covers everything, in seconds. Having good automated testing also makes it easier for other people to understand your code and enables teams to build things together without worrying about breaking each other’s features.
In order to improve the efficiency of test, it is common to break down testing into smaller units that test specific functionalities of the web application. This practice is called unit testing.A unit test verifies the functionality of a component individually .It test one piece independently of other pieces. It is the lowest level of testing the application it makes sure that each aspect of the program works correctly alone.
Unit tests for django applications include:
- Test the model, the model’s methods return the expected data, and the database operation is correct.
- Test form, data validation logic as expected
- Test view, whether the expected response is returned for a particular type of request
- Other methods or classes, etc.
Django provide set of tools that makes testing your web application easy and faultless.Django’s unit tests use a Python standard library module: unittest. This module of django defines tests using a class based approach.
Prerequisites
- Django installed on your computer with a programming environment set up.
- A Django project created with models,urls and views.
Writing Unit Tests
In the application you want test create a new python package named tests.
Testing Urls
In the urls.py file we have three urls that we need to test.
Urls.py
In the tests package created above, create a new python file named test_urls.py and import SimpleTestCase from django.test and import reverse,resolve from django.urls.
test_urls.py
We will create a class called TestUrls and it inherits SimpleTestCase. SimpleTestCase is used when we don’t need to interact with the database.We will create three functions to test three urls.
The reverse() allows to retrieve url details from urls.py file through the name value provided as an argument and the assertEqual() in Python is a unittest library function that is used to check the equality of two values. This function will take two parameters as input and returns a boolean value depending upon the assert condition. If both input values are equal assertEqual() will return true else return false.Same as assertEquals we can use assertTrue(),assertFalse(),assertRaises() etc.
In method test_list_url_resolves(self) assertEquals() will check the resolved url is equal to the project_list view or not if it returns true the testcase will pass else fail.
Testing Views
In the views.py file we have a method project_list() that we need to test.

views.py
In the tests package created above, create a new python file named test_views.py and Import the TestCase from django.test and import reverse from django.urls.

test_views.py
We will create a class called TestViews and it inherits TestCase. setUp() is the first Method that is called before every test function to set up any objects that may be modified by the test .The setUp() method sets up the object that will be used throughout the test class.In the above code we have set self.client equal to the client instance and s_elf.list_url_ equal to the list url .We will be using these in testcases . In function test_project_list_GET(self) we will try to get the project list using list url and store the response in a variable once we get the response we will check if the status code of the response is equal to 200 or not .If the status code is 200 test case will pass .
Testing Models
In the models.py file we have Project Model that we need to test.

models.py
In the tests package created above, create a new python file named test_models.py and import the Test case from django.test.
test_models.py
We will create a class called TestModels and this inherits TestCase. setUp() is first Method that is called before every test function to set up any objects that may be modified by the test.The setUp() method sets up the object that will be used throughout the test class. In the setUp() function we will create the object for model Project .Then test the creation if self.project1.slug is equal to the the name by which project is been created in the setup() function.If both are equal that means project is been created and asserEqual will return True.
The second method that is to be tested under Project model is budget_left

In the above code we have created the object for Model Category and Expense for the project created in setup() and then checked if project1.budget_left is equal to 7000 or not if it is equal test case will pass .
How To Run Test?
To run all the test cases written above run the command : python manage.py test budget (where budget is the name of django app).

Easiest way to run the tests all at once is to use the command python3 manage.py test.
Summary
Writing testing code is neither fun nor glamorous, and is often left to last when creating a website. It is an essential part of making sure that your code is safe to release after making changes, and is cost-effective to maintain.
In this blog I’ve shown you how to write and run tests for your models, urls, and views. There is lot more to know about tests but even with what we’ve learned already we should be able to create effective unit tests for our website.