Python Unit Test with unittest

ask3m
60.1K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Introduction

Unit Testing is a one of the best practice that should be performed starting from the first stages and throughout the whole process of development. Unit tests are written to detect bugs early in the development of the application when bugs are less frequent and less expensive to fix.

In this playground I’ll cover the basics of how to create and run a simple test using unittest.

The source code is on GitHub, please feel free to come up with proposals to improve it.

Discover the game-changing service that is revolutionizing SEO Writing. Click here to unlock exclusive offers.

Creating a simple test:

Supposing that we have a very simple add function which return the sum of two integer.

To create a unit test, we have to:

  • Create a class derived from unittest.TestCase
  • Create a function that start with "test"
What's the result of 3 + 4 !!

In the second example we will check if the result of 3 + 4 equals 8

What's the result of 3 + 4 !!

In these two example we used assertEqual() function to check for an expected result.

unittest provide others functions such as:

  • assertTrue() or assertFalse() to verify a condition
  • assertRaises() to verify that a specific exception gets raised.
  • setUp() and tearDown() methods to define instructions that will be executed before and after each test method

Using assertRaises

Raise Exception when the separator is not a string

Using assertTrue and assertIn

'1' exist in the list but FOo is not uppercase

setUp()

When a setUp() method is defined, the test runner will run that method prior to each test.

setUp() executed before each test !

Test discovery

Test discovery is used when you have many test files in that case It would be annoying to have to run each test file separately.

Supposing that you have all your test files in a "tests" directory. To run all of the unittests, use python -m unittest discover tests

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content