PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

$face = new DBFace("sqlite::memory:");
$face->query("create table user ( id INTEGER PRIMARY KEY, name TEXT )");
$face->query("insert into user (name) values('bob')");
$face->query("insert into user (name) values('harry')");
$this->mapper = new ToolMapper( $face );
}


As you may have gathered, I am not an ideologue when it comes to testing. I routinely “cheat” by
combining real and mocked components, and because priming data is repetitive, I often centralize test
fixtures into what Martin Fowler calls Object Mothers. These classes are simple factories that generate
primed objects for the purpose of testing. Shared fixtures of this sort are anathema to some.
Having pointed out some of the problems that testing may force you to confront, it is worth
reiterating a few points that for my money trump all objections. Testing



  • Helps you prevent bugs (to the extent that you find them during development and
    refactoring)

  • Helps you discover bugs (as you extend test coverage)

  • Encourages you to focus on the design of your system

  • Lets you improve code design with less fear that changes will cause more
    problems than they solve

  • Gives you confidence when you ship code


In every project for which I’ve written tests, I’ve had occasion to be grateful for the fact sooner or
later.


Summary


In this chapter, I revisited the kinds of tests we all write as developers but all too often thoughtlessly
discard. From there, I introduced PHPUnit, which lets you write the same kind of throw-away tests
during development but then keep them and feel the lasting benefit! I created a test case
implementation, and I covered the available assertion methods. I , examined constraints, and explored
the devious world of mock objects. I showed how refactoring for testing can improve design, and
demonstrated some techniques for testing web applications, first using just PHPUnit, and then using
Selenium. Finally, I risked the ire of some by warning of the costs that tests incur and discussing the
trade-offs involved.

Free download pdf