Skip to content

Instantly share code, notes, and snippets.

@drm
Created May 13, 2012 17:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drm/2689365 to your computer and use it in GitHub Desktop.
Save drm/2689365 to your computer and use it in GitHub Desktop.
Example using closures as data provider in PHPUnit
<?php
/**
* @author Gerard van Helden <drm@melp.nl>
*/
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