Sobes.tech
Middle

What is Test-Driven Development (TDD)?

sobes.tech AI

Answer from AI

TDD is a software development methodology based on short iterations: writing a failing test, writing minimal code to pass the test, and refactoring.

TDD cycle:

  1. Red: Write an automated test that describes the required functionality. The test should fail because the functionality is not yet implemented.
  2. Green: Write the minimal amount of code to pass the written test.
  3. Refactor: Optimize and improve the written code, ensuring all tests still pass.

Advantages of TDD:

  • Higher code quality: Tests force writing cleaner and more modular code.
  • Reduced number of errors: Defects are identified early in development.
  • Improved documentation: Tests serve as living documentation of system behavior.
  • Simplified refactoring: Confidence in maintaining functionality thanks to tests.

Tools used in TDD:

  • Unit testing frameworks (JUnit, TestNG)
  • Mocking frameworks (Mockito, PowerMock)

Example of a unit test in JUnit:

// src/test/java/com/example/CalculatorTest.java
package com.example;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CalculatorTest {

    @Test
    void testAdd() {
        Calculator calculator = new Calculator();
        // arrange
        int a = 2;
        int b = 3;
        int expected = 5;

        // act
        int result = calculator.add(a, b);

        // assert
        assertEquals(expected, result);
    }
}

Minimal implementation of the class to pass the test:

// src/main/java/com/example/Calculator.java
package com.example;

public class Calculator {

    public int add(int a, int b) {
        // Minimal code to pass the test
        return a + b;
    }
}