Recipe 20.15. Applying a Unit Test to a Web Page


20.15.1. Problem

Your application is not broken down into small testable chunks, or you just want to apply unit testing to the web site that your visitors see.

20.15.2. Solution

Write a series of unit tests around SimpleTest's WebTestCase class to test the finished output of your web site.

Create a file to test something about your web site, example.com. In a file called exampledotcom_tests.php, put:

class TestOfExampledotcom extends WebTestCase {     // basic homepage loading     function testHomepageLoading()     {         $this->assertTrue($this->get('http://www.example.com/'));     }     // test clicking on "FAQ", and the resulting generation of FAQ     function testFaq()     {         $this->get('http://www.example.com/');         $this->clickLink('FAQ');         $this->assertTitle('Example FAQ');         $this->assertWantedPattern('/have a question\?/i');     } }

require_once 'simpletest/web_tester.php'; require_once 'simpletest/reporter.php'; $test = new GroupTest('Web site tests'); $test->addTestFile('exampledotcom_tests.php'); if (TextReporter::inCli()) {     exit ($test->run(new TextReporter()) ? 0 : 1); } else {     $test->run(new HtmlReporter()); }

20.15.3. Discussion

If you're dealing with a site that's driven in whole or in part by procedural PHP code, it is sometimes difficult to write a smaller unit test that tests encapsulated functionality. Instead, you just want to make sure that the web site is working; if it isn't, you'll debug from there.

Web-page unit testing is a handy technique that is useful whether or not your code base is easily broken into unit tests or not. After all, the real world environment doesn't always behave in the same way as your testing environment, so it can be beneficial to set up a cron job to run a Web Test suite.

The SimpleTest WebTestCase supports testing navigation, content, cookies, and form handling. It can even select frames within framesets to conduct tests within a particular frame.

If your site makes extensive use of JavaScript, take a look at Selenium, an open source testing framework designed to be run in a browser to test the complete user experience. Selenium offers a browser-based IDE that can record actions to automate test generation, and supports a wide range of browsers on Windows, Mac OS X, and Linux.

20.15.4. See Also

Documentation on SimpleTest at http://www.lastcraft.com/simple_test.php; the Selenium project page at http://www.openqa.org/selenium/.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net