Using Data Providers
While it’s possible to create a large number of methods, with each intended to test a different title variation, a more efficient approach might involve using a PHPUnit data provider, which allows you to supply an abundance of test data to a single method. For instance, I’ve placed the following data into a file named
titles.txt
, with each line consisting of a sample Docbook string followed by a confirmation of the expected parsed title.
<title>Hidden Hawaii</title>||||Hidden Hawaii
<title>Gordon's Great Dilemma</title>||||Gordon's Great Dilemma
<title>My title is Physics 101</title>||||My title is Physics 101
Notice how each line introduces a subtle string variation, the first being a “typical” title, the second including a single quote, and the third using the term “title” in the title.
In the test, I’ll configure a data provider method named
loadTitlesProvider()
, which loads each line of the titles.txt
file and splits it according to my designated delimiter (||||
):
public function loadTitlesProvider()
{
$data = array();
foreach (file('titles.txt') as $line) {
$data[] = explode("||||", trim($line));
}
return $data;
}
Next we’ll use the
@dataProvider
annotation to tell the test where the loaded data will be coming from. Because the $data
array consists of two array elements, we’re telling the test that two input parameters will be passed, one for each element:
/**
*
* @dataProvider loadTitlesProvider
*/
public function testParseTitles($docbook, $title)
{
$this->_chapter->setFile($docbook);
$this->_chapter->setTitle();
$this->assertEquals($this->_chapter->getTitle(), $title);
}
Running this test will produce an output consisting of four dots, just what we’re hoping for!
Conclusion
This was but a mere introduction to PHPUnit’s powerful testing facility, but hopefully it helps you get past the initial learning curve. Forthcoming issues will build upon what you’ve learned here, so stay tuned!
About the Author
Jason Gilmore is the founder of EasyPHPWebsites.com and the author of
several popular books, including “Easy
PHP Web sites with the Zend Framework” and “Beginning
PHP and MySQL: From Novice to Professional” (currently in its third edition).
Check out his new DZone reference card, titled “Getting
Started with the Zend Framework.”
several popular books, including “Easy
PHP Web sites with the Zend Framework” and “Beginning
PHP and MySQL: From Novice to Professional” (currently in its third edition).
Check out his new DZone reference card, titled “Getting
Started with the Zend Framework.”