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)
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.
Green – Make the test pass
Write the minimal amount of code needed to make the test pass.
Focus only on passing the test.
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)); } }
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.
| Step | Action | Status |
|---|---|---|
| Red | Write test that fails | Done |
| Green | Write code to make the test pass | Done |
| Refactor | Clean up code without breaking the test | Optional |
No comments:
Post a Comment