
One of the most necessary things when writing unit tests is the creation of mocks and stubs for objects that are used by the class under test. Here it is worth mentioning the important difference: if the “mock” is the original object in which the replacement of one or several methods, then the “stub” is a kind of fake that completely replaces the original object. depending on the scenario, it is sometimes much easier to create a stub than to make a suitable mock. In this article, I will show how to effectively and quickly create stubs using a small Sylph class from the creators of the
PHPixie framework.
Sometimes there are cases when the test method uses deep properties of an object for example:
class Fairy{ public $name; protected $home_tree; public function __construct($name, $home_tree){ $this->name = $name; $this->home_tree = $home_tree; }
When writing a test for such a class, we would have to take the Tree and Forest classes, link them together, and pass them to the constructor. And all for the sake of calling one function.
')
Sylph makes this much easier by using simple associated arrays and anonymous functions. In our case, we could describe $ home_tree as:
$sylph = new \PHPixie\Sylph(); $home_tree = $sylph->cast(array( 'num_squirrels' => 5, 'forest' => $sylph->cast(array( 'num_animals' => function($animal){ if($animal == 'bunny') return 4; throw new \Exception('Animal not found'); } )) ));
This approach has a number of advantages, first of all, much better readability and conciseness.
By the way, the use of anonymous functions allows you to do quite interesting operations, for example, to change parameters on the fly:
$num_bunnies = 5; $bunnies = $sylph->cast(array( 'add' => function($new) use($num_bunnies){ return $new + $num_bunnies; } )); $bunnies->add(1);
As always, the PHPixie developers try to find the easiest solution to the problem.