PHP › Unit Testing with PHPUnit
How does test driven development, commonly abbreviated as TDD, change the typical order in which tests and actual implementation code are written, and what benefits does this workflow claim to offer?
AdvancedAnswer
Test driven development inverts the usual order most developers are accustomed to, by first writing a failing test that clearly describes the exact expected behavior of a piece of functionality that does not yet exist at all, then writing just enough actual implementation code to make that specific failing test pass, and finally refactoring that implementation to improve its internal quality while continuously confirming the test still passes throughout, and proponents argue this disciplined workflow naturally results in more thoroughly tested code, more focused and minimal implementations, and a design that is inherently easier to test from the very beginning, since testability is considered from the very first step rather than added on afterward.
// Step 1: Write a failing test
public function testCalculatesShippingCost(): void
{
$this->assertEquals(5.99, (new ShippingCalculator())->calculate(2.5));
}
// Step 2: Write minimal code to make it pass
// Step 3: Refactor while keeping the test passingReal-world example A developer building a new shipping cost calculation feature writes a failing test describing the exact expected cost for a given package weight before writing any actual implementation code at all, then implements just enough logic to make that test pass.