TEST DRIVEN DEVELOPMENT

Test-Driven Development (TDD)

Test-driven development (TDD) is a software development approach that emphasizes writing tests before writing the actual code. This technique helps developers create software that's more reliable, maintainable, and better aligned with the desired functionality. In TDD, the development process follows a cycle: write a test, make it pass, and then refactor as needed.

The TDD Cycle:


Let's see a code as an example to demonstrate TDD

# test.py

import unittest

import source


class TestCalc(unittest.TestCase):

def testSub1(self):

   self.assertEqual(1, source.performSub(2, 1), "Bug in implementation. Results should be 1.")


def testSub2(self):

   self.assertEqual(10, source.performSub(20, 10), "Bug in implementation. Results should be 1.")


def testDivZero(self):

   self.assertEqual("Put in correct divisor", source.performSub(20, 0), "Bug in implementation.")


if __name__ == '__main__':

unittest.main()

#source.py

def performSub(x, y):

return x - y

4. Run the Test Again: Re-run your test suite. If you've correctly implemented the performSub function, the tests should pass. The "green" phase indicates that your code meets the specified requirements.

5. Refactor (If Needed): If your code is clean and the tests pass, you might consider refactoring to improve readability or performance.


Following the TDD process ensures that your code functions as expected, even as you make changes and enhancements over time. It also provides documentation in the form of tests, which helps you and others understand the code's intended behavior. TDD is a powerful approach for building reliable and maintainable software.