Sobes.tech
Junior — Middle

Is it possible to describe a development approach where tests are written before the implementation of code, and explain its main principles?

sobes.tech AI

Answer from AI

The development approach where tests are written before the code implementation is called Test-Driven Development (TDD) — development through testing.

Main principles of TDD:

  1. Write a test — first, an automated test is created that describes the required behavior or functionality.

  2. Run the test and ensure it fails — since the functionality is not yet implemented, the test should fail.

  3. Write minimal code to pass the test — implement only what is necessary to pass the test.

  4. Refactoring — improve the code while keeping the tests passing.

  5. Repeat the cycle — add new tests and functionality.

TDD helps create more reliable and maintainable code, reduces bugs, and improves design.

Example in Python using unittest:

import unittest

def add(a, b):
    return a + b

class TestAddFunction(unittest.TestCase):
    def test_add_positive(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative(self):
        self.assertEqual(add(-1, -1), -2)

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

First, write the tests, then implement the add function.