Sunday 24 March 2013

Using Data Provider Annotations in PHPUnit - Part2


Today, Let's see how we can create Test case Class that will return Iterator Object using Data Providers Annotation.Before that, if you haven't read part1 of this Post, Please read it first and Proceed below.

Using Data Provider as Iterator object

Let’s create a data provider method which will return object that implements the Iterator interface and yields an array for each iteration - ArrayIterator

Class ContentTest  extends PHPUnit_Framework_TestCase{

 public function contentProvider()
 {
    $content = array(
       array(9,'phpmaster'),
       array(9,'sitepoint'),
       array(3,'php')
    );
    return new ArrayIterator($content);
 }

 /**
  * @dataProvider contentProvider
  */

 public function testContentLength($length,$string)
 {
   $this->assertEquals($length, strlen($string));

 }
}
Only one change when compared to “Using Data Provider as Array of Array” section here is, Instead of returning array of array, we are returning Iterator Object. Please refer Part1 of this Post for detailed explanation regarding test case behavior. You can also write test cases using other iterator objects that PHP Supports like RecursiveArrayIterator, DirectoryIterator and so on.

When I run the above test case in Zend Studio (By Right-Click File name, then select Run as => PHPUnit Test). Following is the test case result.











Hope, you enjoyed this Post.

No comments:

Post a Comment