the least and cheapest thing you could do would be smth like
class Populator
{
private $rowProcessor;
public function __construct($rowProcessor){
$this->rowProcessor = $rowProcessor;
}
public function populate(array $data){
$result = [];
foreach($data as $row){
$result[] = $this->rowProcessor->process($row);
}
return $result;
}
}
general idea is to have some other object injected into Populator
and make it responsible for PopulateMeGently
creation. Don't new
inside because it's uncontrollable and thus untestable.
Concerning names and implementations it could be some Factory
that could implement even methods like makeDefault()
, makeNullPopulateMeGently()
, makeFromRaws($data)
or whatever fits to your design and needs.
No you can mock stuff as:
class PopulatorTest extends PHPUnit_Framework_TestCase
{
private $populator;
private $rowProcessorMock;
public function setUp(){
$this->rowProcessorMock = $this->getMockBuilder('RowProcessor')
->setMethods(array('process'))
->getMock();
$this->populator = new Populator($this->rowProcessorMock);
}
/**
* @test
*/
public function canPopulate(){
$data = array(0, 1);
$this->rowProcessorMock->expects($this->exactly(2))
->method('process')
->withConsecutive(
[$this->equalTo(0)],
[$this->equalTo(1)]
)
->will($this->onConsecutiveCalls('zero', 'one'));
$result = $this->populator->populate($data);
$this->assertSame(array('zero', 'one'), $result);
}
}
the canPopulate
tests all the stuff that needs to happen with $data
-- all its items get processed in order, result is returned as array of tranformed data. Please note that you don't really need to mock out PopulateMeGently
(or whatever you'll rename it to). You just make sure that the thing that is responsible for processing your data is called with appropriate parameters and its results are returned appropriately.