Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TDD with PHPUnit

TDD with PHPUnit

A real world example of using TDD in a project

Anler

May 26, 2012
Tweet

More Decks by Anler

Other Decks in Programming

Transcript

  1. “Even good programmers make mistakes. The difference between a good

    programmer and a bad programmer is that the good programer uses tests to detect his mistakes as soon as possible...” -- phpunit manual 3 Friday, March 30, 12
  2. write tests FAIL implementation SUCCESS REFACTOR: go back to 1

    and start again 1 2 3 4 6 Friday, March 30, 12
  3. “Whenever you are tempted to type something into a print

    statement or a debbuger expression, write it as a test instead” -- Martin Fowler 7 Friday, March 30, 12
  4. Create a composer.json in your project’s root directory: That will

    install PHPUnit under YourProject/vendor/ directory Then use the installed phpunit.php executable Then simply do: composer.phar install/update to install/update dependencies 12 Friday, March 30, 12
  5. Drop a phpunit.xml.dist file in your project’s directory with this

    configuration: bootstrap.php is used to setup the test environment 14 Friday, March 30, 12
  6. Changes in the core in order to make it more

    “testeable”: Wrap $_ superglobals in more semantic objects suchas request and response Bootstrap test file is a mess due to all those F*** super global constants: DON’T USE CONSTANTS OR SINGLETONS, USE DEPENDENCY INJECTION Setup a test database (easy but don’t forget to use MyISAM as the database engine) We had to refactor the codebase in order to: 16 Friday, March 30, 12
  7. Add the following to the phpunit.xml.dist file That tells DBUnit

    how to connect to the test database 18 Friday, March 30, 12
  8. Create the file tests/DatabaseTestCase.php: getDataSet() is something I did to

    ease fixtures load in my test cases 19 Friday, March 30, 12
  9. Fixtures: “I want my DB with this data when running

    this test” 20 Friday, March 30, 12
  10. I usually name fixtures after the test case. For example

    when I’m testing: tests/AddBuyer/Tests/RegistrationTest.php I load the fixture: tests/AddBuyer/Fixtures/RegistrationTest.yml test case fixture 21 Friday, March 30, 12