dagfinn | 28 January, 2008 13:53
I follow the principle that you should test everything that could possibly fail. And I would like to have unit tests for everything; tests that exercise each small behavior in isolation. The components that are easiest to unit test are typically class and methods in plain object-oriented code. Not everything falls into that category, though. Page templates, XSLT and other XML files are some counterexamples.
As I mentioned in my blog post on Paparrazzi testing, Uncle Bob (Robert C. Martin) has discussed how to test web templates or server pages. Since I'm currently working with Smarty templates, I wanted a simple way to run tests on them without needing to deal with a web server and the page navigation in a full web application.
Simpletest's web tester has a simplified web browser that's capable of running HTTP requests to test an actual running web application. To test a Smarty template in isolation, we can replace it with something even simpler that talks directly to the Smarty template engine instead of the web server. It's this simple:
class SmartyBrowser {
private $smarty;
private $template;
function __construct($smarty,$template) {
$this->smarty = $smarty;
$this->template = $template;
}
function getContent() {
return $this->smarty->fetch($this->template);
}
}
getContent() can replace the getContent() method of Simpletest's built-in browser (SimpleBrowser), enabling SimpleTest to run all the usual assertions on the generated HTML page. To make this happen we replace the SimpleBrowser instance with the SmartyBrowser: <?php
class SomeTemplateTest extends UnitTestCase {
function setUp() {
$this->smarty = new Smarty;
$this->_browser = new SmartyBrowser($smarty,'page.tpl');
}
Also, we need the usual Smarty directory setup.
Now we can test Smarty output. What would be really interesting, but much more complex, would be to extend the concept to actually testing two-way interaction between the server / template and the client / browser.
| « | January 2008 | » | ||||
|---|---|---|---|---|---|---|
| Su | Mo | Tu | We | Th | Fr | Sa |
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 31 | ||