Test Driven Development

- 220 words - 2 minutes

A unit is a class or a function. A test is running the unit and checking the result against and expected, designed value.

A unit might need more than one test, to check the result when using parameters for different designed scenarios.

If the unit uses other units when it executes, some setup might be required to isolate the unit under test, by creating mocks of the other units. Those mocks need to be tore down after the test.


Follow these steps for each unit [1] :

  1. Design

  2. Test fails

  3. Implement

  4. Test passes

Test template

import unittest

class Function(unittest.TestCase):
  def test_case(self):
      from module import function
      result = function()
      expected = 5
      self.assertEqual(result, expected)

If unit isolation is needed:

  def setUp(self):
  def tearDown(self):


Mocks are callable and create attributes as new mocks when you access them [2] . The return value of calling the mock can be set either way:

function = Mock(return_value=True)

function = Mock()

Frequently used methods:

function.assert_called_with(*argv, **kwargs)
function.assert_called_once_with(*argv, **kwargs)

Frequently used attributes:


Setting up and tearing down the mock for a built-in function, for example input():

  def setUp(self):
      from unittest.mock import Mock
      import module

      module.input = Mock(return_value='y')
  def tearDown(self):
      import module

      del module.attribute


  1. Introducción a Test Driven Development, presented in LinuxCabal, March 24th, 2012, PDF, Video
  2. The Mock Class