Thursday, February 11, 2010

PHPUnit with Zend View

When you want to check if important objects in Zend Views show up using PHPUnit testing can be used. In my case I have a registration form which repopulated the fields if one was missing or if anything was incorrectly filled in.

There seem to be multiple ways to select elements in the DOM:
- assertQuery - CSS selector
- assertXpath - Xpath selector
- strpos (!) - search through the html as a string

I first tried CSS selector:
$this->assertQuery('input[id="username"][value="test1"]'); //username
$this->assertQuery('input#username[value="test1"]'); //username
$this->assertQuery("input[value='']"); //emailaddress

All should work, but there are different problems. The two first selections don't work, event though they work in firebug. The last line doesnt work either because of the period '.' which gives a "DOMXPath::query(): Invalid predicate" error.
Seems Zend PHPUnit converts from CSS to Xpath selectors and doesnt manage to do it right.

Therefore using Xpath directly is better. (Download the FireXpath extension to Firebug for Firefox and play around to learn it (also is good)). So here's Xpath:
$this->assertXpath("//input[@id='username'][@value='test1']"); //username
$this->assertXpath("//input[@id='emailaddress'][@value='']"); //emailaddress

Works out of the box.

Alternatively you can search through the html code linearly:
$this->assertTrue(strpos($this->_response->getBody(), '') !== false); //emailaddress
However, if anything changes in the html code, the test might fail.

Solution sources:,, others I cant remember.


  1. Thanks for the xpath examples, I was trying to assert that elements had particular values the same way you were and you saved me a bunch of time.

  2. @curmil - Great! :) I remember messing around with the different selectors for quite a while before getting the XPath to work. I think XPath selectors are clearer than CSS selectors.