Unit Testing

This is used for testing if our classes and methods work in the way we desire all the time

Use case scenario

1) Suppose we create a model class User

2) After writing this model, we may want to check if we are able to create a new user successfully

Creating a unit test

1) Create a class that extends django.test.TestCase and methods in this class starting with test will be executed when the following command is run

python manage.py test

2) Unit test cases should be implemented in files (or dirs) starting with test.

Example

1) In File tests/test_models.py, we test if we are able to create a new user

from django.test import TestCase
    from django.contrib.auth import get_user_model


    class ModelTests(TestCase):

        def test_create_user_with_email_successful(self):
            email = 'silent@retreat.com'
            password = '1234'

            # get_user_model() returns the default user model.
            # If it has to return custom usermodel, create a new model
            # and in settings.py Set AUTH_USER_MODEL pointing to custom model
            user = get_user_model().objects.create_user(
                email=email,
                password=password
            )

            self.assertEqual(user.email, email)
            self.assertTrue(user.check_password(password))

2) Run

python manage.py test

3) This test will fail because default user model requires mandatory Username field. So we cannot create user with email alone

Creating custom user mmodel will be seen in next section