Refactor and Improve the Test

Learn to improve the test method using docstrings.

In this lesson, we refactor our test methods. The purpose of this refactoring is to improve the method by making it more descriptive. We use the Python document string also called the docstring for this.

What are docstrings?

To add comments to our code in Python, we use the # symbol, as shown below:

def sayHello():
    # prints hello world to the screen
    print("Hello World")

We can also use docstrings to add comments. Additionally, they can be used to document our code, especially classes, functions, methods, and modules.

def sayHello():
    """    
    prints hello world to the screen
    """
    print("Hello World")

The Django unit testing framework uses docstrings. Docstrings describe what each test method does.

Therefore, when we get a failing test, we can also see a short description of the test’s method we create. This applies to all failed tests except the AssertionError.

Add docstrings to the test method

Here’s an example of how we can add docstrings to a particular test method:

Get hands-on with 1200+ tech skills courses.