Search⌘ K
AI Features

Unit Testing

Explore how to write and organize unit tests in Python using the unittest framework. Understand test case design, key assertion methods, setup and teardown processes, and how to bundle tests into suites for effective code validation.

Introduction and structure of unit testing

A unit test tests the methods in a single class. A test case tests the response of a single method to a particular set of inputs.

To do unit testing, you have to do the following:

  • import unittest
  • import fileToBeTested or from fileToBeTested import *

    Reminder: If you use from file import * you don’t have to precede every function call with the name of the file it was imported from. ...

  • Write a class SomeName(unittest.TestCase). Within the class:
    • Define methods setUp(self) and tearDown(self), if desired. These are both optional.
    • Provide one or more testSomething(self) methods. You may include other methods, but the names of test methods must begin with test.
  • At the end of the test file, put unittest.main().