Python Examples
Convert IP to Integer and Integer To IP in Python How to Get IPv4/IPv6 Address Range from CIDR in Python? Compare Two Objects For Equality in Python How to find Duplicate Elements from a List in Python Convert Timestamp to datetime in Python Convert datetime to Timestamp in Python Generate Random String of Specific Length in Python Encryption and Decryption of Strings in Python The string module in Python Convert string to bytes in Python Convert bytes to string in Python Convert string to datetime and datetime to string in Python Call a function Asynchronously from within a Loop and wait for the Results in Python Remove Duplicate Elements from a List in Python Caching in Python with Examples How to Bulk Insert and Retrieve Data from Redis in Python How to Write Unit Test in Python Read and Write CSV Files in Python Read and Write Data to a Text File in Python How to Convert CSV to JSON in Python Create ICS Calendar File in Python Install Python on Windows 10/11 Install Python on Ubuntu 20.04 or 22.04.3 Python - Install Virtual Environment How to Find a Specific Field Value from a JSON list in Python Download and Unzip a Zipped File in Python Python Install PIP Python Install Virtual Environment How to Fix Python Error: string argument without an encoding Compare Two JSON files in Python How to Hash a Dictionary Object in Python? Create a Digital Clock in Python Create Multiple URLs Using Each Path of a URL in Python Send an Email with Multiple Attachments using Amazon SES in Python SQLAlchemy Query Examples for Effective Database Management SQLAlchemy Query to Find IP Addresses from an IP Range in Bulk How to Create and Use Configuration files in a Python Project Check if a Value Already Exists in a List of Dictionary Objects in Python How to Split Large Files by size in Python? Fixing - Running Scripts is Disabled on this System Error on Windows Generating QR Codes in Python Reading QR Codes in Python

Writing Unit Tests in Python

  • Last updated Apr 25, 2024

Unit tests are written to verify the functionality of a specific piece of code, ensuring that it works as intended. These tests confirm that your code functions correctly and that the inputs and outputs align with your expectations.

Writing unit tests in Python is an essential part of ensuring the correctness and robustness of your code. Python provides a built-in module called unittest for writing and running unit tests.

Here's how to write unit tests in Python using the unittest framework:

  1. Importing the unittest module:
  2. Start by importing the unittest module at the beginning of your test file:

    import unittest
  3. Creating a test Class:
  4. Create a test class that inherits from unittest.TestCase. This class will contain your test methods. For example:

    class MyTestCase(unittest.TestCase):
  5. Writing test methods:
  6. Create individual test methods within your test class. Test method names should start with the word "test" to be automatically discovered by the test runner. For example:

    def test_addition(self):
        expected_result = 14
        result = 10 + 4
        self.assertEqual(result, expected_result)
    def test_subtraction(self):
        expected_result = 10
        result = 15 - 5
        self.assertEqual(result, expected_result)

    In these examples, assertEqual is an assertion method provided by unittest to check if the given expression is true.

  7. Using set up and tear down methods (Optional):
  8. If your tests require some common setup or cleanup, you can use setUp and tearDown methods within the test class. These methods will be called before and after each test method, respectively. For example:

    def setUp(self):
        # Set up any resources or configurations needed for the tests.
    def tearDown(self):
        # Clean up after each test.
  9. Running the tests:
  10. To run your unit tests in Python, you can run the tests from the command line using the following command:

    python -m unittest
Complete Example

Here's a complete example that demonstrates how to create unit tests using the Python unittest library for a my_calculator module:

def addition(a, b):
    return a + b

def subtraction(a, b):
    return a - b
import unittest
import my_calculator

class CalculatorTestCase(unittest.TestCase):

    def setUp(self):
        self.num1 = 10
        self.num2 = 5

    def test_addition(self):
        print("testing addition...")
        expected_result = 15
        result = my_calculator.addition(self.num1, self.num2)
        self.assertEqual(result, expected_result)

    def test_subtraction(self):
        print("testing subtraction...")
        expected_result = 5
        result = my_calculator.subtraction(self.num1, self.num2)
        self.assertEqual(result, expected_result)

    def tearDown(self):
        print("cleaning up...")
        self.num1 = 0
        self.num2 = 0

if __name__ == "__main__":

In this example, we began by creating a testcase class named CalculatorTestCase, by subclassing unittest.TestCase. The two individual test methods, whose names start with the letters "test", inform the test runner about which methods represent tests. The setUp() method is used to initialize the test fixture and is executed before any test method runs. The tearDown() method is used to clean up resources and is executed after each test method. The assertEqual() function checks the two provided values for a true condition.

The output of the above unit test is as follows:

testing addition...
cleaning up...
testing subtraction...
cleaning up...
Ran 2 tests in 0.001s