Return to site

☕🧪 TDD: write the TEST before the CODE

TDD asks one simple question first: how will you prove it works? 🔄

· testing

🔸 TLDR

TDD ( Test-Driven Development ) follows a simple cycle:

▪️ Write a failing test 🔴

▪️ Write the minimum code to pass 🟢

▪️ Refactor safely 🔵

▪️ Repeat 🔁

RED ➡️ GREEN ➡️ REFACTOR

🔸 WHAT IS TDD?

Instead of writing production code first and tests later, TDD reverses the order.

Example:

@Test void shouldApplyTenPercentDiscount() {
    var calculator = new DiscountCalculator();
      assertEquals(90,
         calculator.calculate(100, 10)); }

At first, the test fails. 🔴

Then write the minimum implementation:

class DiscountCalculator {
      double calculate(double price, double discount) {
         return price - price * discount / 100;
     } }

Now the test passes. 🟢

Then refactor while keeping it green. 🔵

The test becomes both a specification and a regression safety net.

🔸 TDD IS NOT YOUR WHOLE TEST STRATEGY

TDD is commonly used with unit tests because they are fast and isolated.

But production systems need more.

▪️ UNIT TESTS

Business rules, classes and functions.

Tools: JUnit, Mockito, AssertJ.

▪️ INTEGRATION TESTS

Verify components working together.

Spring + database + Kafka + external services.

Tools: Spring Boot Test, Testcontainers.

▪️ API TESTS

Validate REST endpoints, status codes and payloads.

Example: MockMvc, REST Assured.

▪️ CONTRACT TESTS

Ensure consumers and providers remain compatible.

Tools: Pact, Spring Cloud Contract.

▪️ END-TO-END TESTS

Validate complete user journeys.

Login ➡️ Order ➡️ Payment ➡️ Confirmation

Tools: Playwright, Selenium, Cypress.

🔸 THE TESTING PYRAMID

E2E

Integration

Unit Unit Unit

Many fast unit tests.

Fewer integration tests.

Even fewer E2E tests.

TDD mainly strengthens the foundation.

🔸 TAKEAWAYS

▪️ TDD = TEST → CODE → REFACTOR

▪️ RED-GREEN-REFACTOR encourages small changes

▪️ Tests act as executable specifications

▪️ TDD improves confidence during refactoring

▪️ Unit tests alone are not enough

▪️ Complete them with integration, API, contract and E2E tests

TDD does not eliminate bugs.

It makes expected behavior explicit before implementation. 🧪

#java #tdd #testing #junit #softwaretesting #testautomation #springboot #softwareengineering #javadeveloper

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaFullstackBook👇