Python – What is TDD (Test-Driven Development) ?

What is TDD ?

TDD (Test-driven development) is software design approach where your code is written around your tests.

With TDD the test is first created, this test initially fails. The minimum amount of code is then written to ensure the test passes. This approach provides the following benefits,

  • promotes the creation of more efficient code
  • improves code quality
  • ensures the minimum amount of code is used
  • prevents code regression

Example

Within our example we will use the Python module unittest to show the process of creating a simple class based on TDD.

Write Test

First of we write our test. Our test will pass if our code returns the number 6.

import unittest
from calculator import Calculator

class TestCalculatorCase(unittest.TestCase):
    def setUp(self):
        pass
    
    def test_multiply(self):
        calc = Calculator()
        self.assertTrue(calc.multiply(2, 3) == 6)

if __name__ == '__main__':
    unittest.main()

Result

Of course when the test is run it fails as we have yet to write any code.

======================================================================
ERROR: test_multiply (__main__.TestCalculatorCase)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "<stdin>", line 9, in test_multiply
NameError: global name 'Calculator' is not defined
 ----------------------------------------------------------------------
Ran 1 tests in 0.001s FAILED (errors=1)

Write Code

We then write are code so that it passes based on our test.

class Calculator(object):
    def multiply(self, a, b):
        return a*b

Final Test

We then rerun our test and as we now have the required code it passes.

----------------------------------------------------------------------
 Ran 1 test in 0.001s
 OK
Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial