Java Test Driven Development
In this page:
What is Test Driven Development?
Test Driven Development (TDD) is a development process where you write an automated test before writing the production code that makes it pass. It follows a strict Red-Green-Refactor cycle, which forces you to think through a feature's expected behavior before you start implementing it.
Example: What is Test Driven Development?
public class Main {
public static void main(String[] args) {
// Red -> Green -> Refactor
System.out.println("Write the test before the production code that makes it pass");
}
}
Login to try C/C++/Java/PHP code in the editor
The Red Phase
The Red Phase is the first step: you write a test for a feature that doesn't exist yet, and confirm it fails. This both clarifies exactly what the feature needs to do and proves the test is actually capable of catching a failure, rather than passing vacuously.
Example: The Red Phase
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class Main {
static int add(int a, int b) { return 0; } // not implemented yet -- test should fail
@Test
void testAdd() {
assertEquals(5, add(2, 3)); // fails: proves the test can actually catch a wrong result
}
public static void main(String[] args) {
System.out.println("Red: test written, expected to fail against the stub");
}
}
Login to try C/C++/Java/PHP code in the editor
The Green Phase
The Green Phase comes next: you write the minimum amount of production code needed to make the failing test pass, even if that code isn't elegant or fully optimized yet. The goal here is correctness first, not polish.
Example: The Green Phase
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class Main {
static int add(int a, int b) { return a + b; } // minimal code to pass, not yet polished
@Test
void testAdd() {
assertEquals(5, add(2, 3));
}
public static void main(String[] args) {
new Main().testAdd();
System.out.println("Green: test now passes");
}
}
Login to try C/C++/Java/PHP code in the editor
The Refactor Phase
The Refactor Phase is where you clean up, simplify, and reorganize the code you just wrote, running the test suite continuously as you go to confirm your changes haven't broken any existing behavior along the way.
Example: The Refactor Phase
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class Main {
static int add(int... numbers) { // cleaned up to accept any count of numbers
int sum = 0;
for (int n : numbers) sum += n;
return sum;
}
@Test
void testAdd() {
assertEquals(5, add(2, 3)); // still passes after refactoring
}
public static void main(String[] args) {
new Main().testAdd();
System.out.println("Refactor: cleaned up, tests still green");
}
}
Login to try C/C++/Java/PHP code in the editor
TDD for Web Utilities
TDD is especially valuable for building robust, reusable utilities: writing the tests first for background calculations running on a site like cookiescursor.com ensures those calculations are fully verified and unlikely to regress silently before they ever reach production.
Example: TDD for Web Utilities
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class Main {
static double discount(double price, double percent) { return price - (price * percent / 100); }
@Test
void testDiscount() {
assertEquals(90.0, discount(100.0, 10.0)); // background calculation verified before shipping
}
public static void main(String[] args) {
new Main().testDiscount();
System.out.println("Discount calculation verified via test-first development");
}
}
Login to try C/C++/Java/PHP code in the editor
- Writing large blocks of production code before writing any automated tests, violating TDD guidelines.
- Skipping the Refactor Phase, which leads to messy and hard-to-maintain codebases over time.
- Writing tests that are too complex or check too many things at once, making bugs difficult to isolate.
- Test Driven Development is a strict Red-Green-Refactor development cycle.
- Write a failing test first (Red), implement minimum code to pass (Green), and optimize the code while keeping tests green (Refactor).
- TDD ensures highly reliable code, prevents regression bugs, and improves your software design architecture.
Standard Java testing and assertion structures are supported natively by all Java development kits.
Chapter Quiz — Complete all 19 topics to unlock
0/19 topics done
Complete these topics first:
- Java Reflection API
- Java Annotations Advanced
- Java Garbage Collection
- Java Memory Management
- Java Performance Optimization
- Java Advanced Interview Questions
- Java CompletableFuture
- Java Atomic Classes
- Java Locks & Semaphores
- Java Concurrent Collections
- Java Cryptography Basics
- Java Hashing (MD5, SHA)
- Java SSL & HTTPS
- Java Logging (Log4j/SLF4J)
- Java Serialization Advanced
- Java Interview Questions Advanced
- Java Connection Pooling
- Java Test Driven Development
- Java Integration Testing