Created
May 13, 2012 17:21
-
-
Save drm/2689365 to your computer and use it in GitHub Desktop.
Example using closures as data provider in PHPUnit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Gerard van Helden <[email protected]> | |
*/ | |
class FooBuilder { | |
protected $properties = array(); | |
function add($property, $value) { | |
$this->properties[$property][] = $value; | |
return $this; | |
} | |
function remove($property) { | |
if (!empty($this->properties[$property])) { | |
array_pop($this->properties[$property]); | |
if (count($this->properties[$property]) == 0) { | |
unset($this->properties[$property]); | |
} | |
} | |
return $this; | |
} | |
function build() { | |
return $this->properties; | |
} | |
} | |
class FooBuilderTest extends \PHPUnit_Framework_TestCase { | |
/** | |
* @dataProvider builderCases | |
*/ | |
function testBuildingWithFluentInterfaceWillResultInExpectedArray($expected, $builderImpl, $description) { | |
$builder = new FooBuilder(); | |
$this->assertEquals($expected, $builderImpl($builder)->build(), $description); | |
} | |
function builderCases() { | |
return array( | |
array( | |
array(), | |
function (FooBuilder $builder) { | |
return $builder; | |
}, | |
"Initial construction" | |
), | |
array( | |
array('a' => array('b')), | |
function (FooBuilder $builder) { | |
return $builder->add('a', 'b'); | |
}, | |
"Adding single property" | |
), | |
array( | |
array('a' => array('b', 'c')), | |
function (FooBuilder $builder) { | |
return $builder | |
->add('a', 'b') | |
->add('a', 'c') | |
; | |
}, | |
"Adding single property twice" | |
), | |
array( | |
array('a' => array('b', 'c'), 'x' => array('y', 'z')), | |
function (FooBuilder $builder) { | |
return $builder | |
->add('a', 'b') | |
->add('a', 'c') | |
->add('x', 'y') | |
->add('x', 'z') | |
; | |
}, | |
"Adding different properties multiple times" | |
), | |
array( | |
array('a' => array('b', 'c'), 'x' => array('y', 'z')), | |
function (FooBuilder $builder) { | |
return $builder | |
->add('a', 'b') | |
->add('x', 'y') | |
->add('x', 'z') | |
->add('a', 'c') | |
; | |
}, | |
"Adding different properties multiple times in a different order" | |
), | |
array( | |
array('x' => array('y', 'z'), 'a' => array('b', 'c')), | |
function (FooBuilder $builder) { | |
return $builder | |
->add('x', 'y') | |
->add('x', 'z') | |
->add('a', 'b') | |
->add('a', 'c') | |
; | |
}, | |
"Adding different properties multiple times in a different order" | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment