What is TDD and how to use JUnit as TDD

  

What is TDD (Test-Driven Development)?

Test-Driven Development (TDD) is a software development methodology where you write tests before writing actual code. The main goal of TDD is to improve the design, quality, and maintainability of code.


TDD Workflow (The Red-Green-Refactor Cycle)

  1. Red – Write a failing test

    • Write a test case for the desired functionality before writing the code.

    • Since the code doesn’t exist yet, the test will fail.

  2. Green – Make the test pass

    • Write the minimal amount of code needed to make the test pass.

    • Focus only on passing the test.

  3. Refactor – Improve the code

    • Clean up the code while ensuring that all tests still pass.

    • Improve readability, remove duplication, optimize logic.

This cycle continues for each new piece of functionality.


Benefits of TDD

  • Forces requirement clarity before implementation.

  • Results in better design and decoupled components.

  • Reduces bugs due to automated tests.

  • Makes refactoring safe (you have tests as safety net).

  • Improves developer confidence and code coverage.


How to Use JUnit for TDD in Java

JUnit is a widely used testing framework in Java, perfect for TDD.


TDD Example with JUnit

Let’s develop a method to check if a number is prime using TDD.


Step 1: Write Failing Test


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

public class PrimeUtilTest {

    @Test
    public void testIsPrime() {
        assertTrue(PrimeUtil.isPrime(5));  // test will fail: isPrime not implemented
        assertFalse(PrimeUtil.isPrime(4));
        assertTrue(PrimeUtil.isPrime(2));
    }
}




Step 2: Write Minimal Code to Pass


public class PrimeUtil {

    public static boolean isPrime(int number) {
        if (number <= 1) return false;
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) return false;
        }
        return true;
    }
}



Step 3: Refactor if Needed

  • You can extract logic, rename variables, or make code cleaner.

  • No need to change behavior; just improve structure.



Best Practices When Using JUnit for TDD

  • Use descriptive names for tests (testAddTwoNumbersReturnsSum)

  • Start simple; avoid over-engineering.

  • Test both positive and negative cases.

  • Use tools like Maven or Gradle for test automation.

  • Keep test methods independent and isolated.




At a glance:


StepActionStatus
RedWrite test that failsDone
GreenWrite code to make the test passDone
RefactorClean up code without breaking the testOptional