I've been working on Wordpress plugins lately, and the amount of legacy code is phenomenal. To cope with that, here's a recipe I use for making little islands of sanity:

  1. Install prerequisites

    1. composer: I used brew install composer.
    2. PHPUnit composer require --dev phpunit/phpunit ^11
  2. Add a test script in composer.json

    {
        "scripts": {
            "test": "phpunit tests"
        },
        "require-dev": {
            "phpunit/phpunit": "^11"
        }
    }
    
  3. Run tests on a file change with entr.

    find . | entr -c composer run test
    
  4. TDD new pieces of code before embedding them in legacy code.

    <?php
    declare(strict_types=1);
    class Klass {
        public function something($val): bool {
            return $val;
        }
    }
    ?>
    
    <?php
    declare(strict_types=1);
    use PHPUnit\Framework\TestCase;
    
    final class KlassTest extends TestCase {
        private $klass;
    
        protected function setUp(): void
        {
            $this->klass = new Klass();
        }
    
        public function testOne(): void {
            $this->assertFalse($this->klass->something(false));
            $this->assertTrue($this->klass->something(true));
        }
    }
    ?>
    
  5. Enjoy the tranquility of making changes to tested code. 😌

Back to all posts