PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 18 ■ TESTING WITH PHPUNIT

$this->assertTrue($this->isTextPresent("no name provided"));
} catch (PHPUnit_Framework_AssertionFailedError $e) {
array_push($this->verificationErrors, $e->toString());
}
$this->type("venue_name", "my_test_venue");
$this->click("//input[@value='submit']");
$this->waitForPageToLoad("30000");
try {
$this->assertTrue($this->isTextPresent("'my_test_venue' added"));
} catch (PHPUnit_Framework_AssertionFailedError $e) {
array_push($this->verificationErrors, $e->toString());
}
$this->type("space_name", "my_test_space");
$this->click("//input[@value='submit']");
$this->waitForPageToLoad("30000");
try {
$this->assertTrue($this->isTextPresent("space 'my_test_space' added"));
} catch (PHPUnit_Framework_AssertionFailedError $e) {
array_push($this->verificationErrors, $e->toString());
}
}
}


I changed the default browser from 'chrome' to 'firefox.' Apart from that, I have made no changes at
all to this test. Remember that I started the Selenium Server a while back. This must be running, or
PHPUnit tests that use Selenium will fail. It is the server that launches the browser (Firefox in this case,
though most modern browsers are supported for running tests).
With the test saved and the server running I can execute my test case:


$ phpunit seleniumtest.php


PHPUnit 3.4.11 by Sebastian Bergmann.
.
Time: 11 seconds, Memory: 4.00Mb
OK (1 test, 3 assertions)


If you run the test, not only will you see this output, you’ll see a browser window pop up, invoked by
the server, and the actions executed at lightning speed. The sort of point and click grunt work that we
used to have to do by hand, neatly automated.
Of course I’ve only just scratched the surface of Selenium here. But hopefully it’s enough to give you
an idea of the possibilities. If you want to learn more, there is a complete Selenium manual at
http://seleniumhq.org/docs/index.html. You should also take a look at the Selenium documentation on
the PHPUnit site at http://www.phpunit.de/manual/current/en/selenium.html.


A Note of Caution


It’s easy to get carried away with the benefits that automated tests can offer. I add unit tests to my
projects, and I use PHPUnit for functional tests as well. That is, I test at the level of the system as well as
that of the class. I have seen real and observable benefits, but I believe that these come at a price.

Free download pdf