PyUnit Tutorial: Python Unit Testing Framework (with Example)

What is Unit Testing?

Unit Testing in Python is done to identify bugs early in the development stage of the application when bugs are less recurrent and less expensive to fix.

A unit test is a scripted code level test designed in Python to verify a small "unit" of functionality. Unit test is an object oriented framework based around test fixtures.

Python Unit Testing Techniques

Python Unit Testing mainly involves testing a particular module without accessing any dependent code. Developers can use techniques like stubs and mocks to separate code into "units" and run unit level testing on the individual pieces.

Python Unit Testing Framework

To make the Unit Testing process easier and improve the quality of your project, it is recommended the Python Unit Testing Framework. The Unit Testing framework includes

PyUnit Tutorial: Learn Python Unit Test Framework with Example

Unit Testing with PyUnit

Pyunit is a Python port of JUnit. As a part of Pyunit, in the unittest module there are five key classes.

PyUnit Tutorial: Learn Python Unit Test Framework with Example

Designing a test case for Python Testing using PyUnit

A unit test provides a base class, test case, which may be used to create new test cases. For designing the test case, there are three sets of methods used are

PyUnit Tutorial: Learn Python Unit Test Framework with Example

unittest.TestCase
setUp()
teardown()

skipTest(aMesg:string)
fail(aMesg:string)

id():string
shortDescription():string

In the first set are the pre and post test hooks. The setup() method begins before each test routine, the teardown() after the routine.

The second set of method controls test execution. Both methods take a message string as input, and both cancel an ongoing test. But the skiptest() method aborts the current test while the fail() method fails it completely.

The last or third method help determining the test. The method id() returns a string consisting of the name of the testcase object and of the test routine. And the method shortDescription() returns the docstr comment at the initiation of each test routine.

Advantages of using Python Unit testing

 

YOU MIGHT LIKE: