tdd-deciphered.com

created by @parsingphase

Chapter 5: Introducing the tests

Having specified our system architecture in Chapter 3, and our class namespaces in Chapter 4, we now need to combine these by creating tests and code. We’re going to take a test-first approach here, so let’s test our decision that our Rotors implement the Enigma Encryptor Interface:

In our test file tests\Phase\Enigma\RotorTest.php, we add:

<?php
namespace Phase\Enigma;

class RotorTest extends \PHPUnit_Framework_TestCase
{
    public function testRotorIsAnEncryptor ()
    {
        $rotor = new Rotor();
        $this->assertTrue($rotor instanceof EncryptorInterface, "Rotor must support EncryptorInterface");
    }
}

This is a perfectly valid test, even though the classes it purports to test don’t exist yet. If it tells us so when it runs, it’s entirely correct as a test. We can check this by running PHPunit, which will find all classes in a given directory with names ending in “Test”, call all methods in those classes whose names start with “test”, and report on the validity of all $this->asserts calls:

enigma-simulator$ ./vendor/bin/phpunit tests

give us:

PHP Fatal error:  Class 'Phase\Enigma\Rotor' not found 

Let’s fix this one step at a time, the TDD way.

Create the missing class file in src\Phase\Enigma\Rotor.php. This can be an empty class for the moment:

<?php
namespace Phase\Enigma;

class Rotor
{
}

Conveniently, because we’re using the copy of phpunit that composer installed, phpunit already has access to the autoloader paths we specified above, so it finds the class, fails the call to “assert True()” and reports:

There was 1 failure:

1) Phase\Enigma\RotorTest::testRotorIsAnEncryptor
Rotor must support EncryptorInterface
Failed asserting that false is true.

Which is entirely valid as the Rotor doesn’t support that interface. Let’s fix that:

In src/Phase/Enigma/EncryptorInterface.php:

<?php
namespace Phase\Enigma;

interface EncryptorInterface {
}

(note that we’re not adding any functions yet as our tests don’t cover them).

In src\Phase\Enigma\Rotor.php, add the implements clause:

class Rotor implements EncryptorInterface

and retest. No errors are reported, and we see:

OK (1 test, 1 assertion)

(For added satisfaction, if you have full colour vision, run the test command as
./vendor/bin/phpunit --color tests )

Once more, we’ve made a useful step forward, so git commit the code. I’ve tagged this stage on github as Chapter5-1-FirstTest

Now that we know what our testing rig looks like, we can move on to start simulating real hardware.