The mock object instrument for PHP unit tests
Delusion is a testing instrument for programmers and quality engineers that helps them to test PHP projects by giving ability to mock and stub any not build-in objects in realtime. It's works only with projects which uses Composer.
It's very easy to use Delusion in your tests. First of all you must inject it before all tests. You can use bootstrap
parameter in PHPUnit or Unteist configuration to specify path to bootstrap file.
In this file you need to include Composer autoload first if it's not included yet (does not need in case of using Unteist framework) and start Delusion injection. Bootstrap file may looks like this:
<?php
require 'vendor/autoload.php';
\Delusion\Delusion::injection();
Now you can controll all instances and static classes loaded after last line.
At the first blush, you will not see the difference. You can check class name, interface, methods and variables. You can invoke any methods and you will get real object behavior. Lets check it with simple class.
<?php
// file SimpleClass.php
class SimpleClass extends SplDoublyLinkedList
{
public $var = 2;
public function __construct($var = null)
{
if ($var !== null) {
$this->var = $var;
}
}
public function getVar()
{
return $this->var;
}
}
Now we will check class behavior.
<?php
// First instance
$class1 = new SimpleClass;
get_class($class1); // SimpleClass
is_subclass_of($class1, 'SplDoublyLinkedList'); // true
is_subclass_of($class1, 'SplFixedArray'); // false
$class1->var; // 2
$class1->getVar(); // 2
// Second instance (with parameter in constructor)
$class2 = new SimpleClass(3);
get_class($class1); // SimpleClass
is_subclass_of($class1, 'SplDoublyLinkedList'); // true
is_subclass_of($class1, 'SplFixedArray'); // false
$class1->var; // 3
$class1->getVar(); // 3
Looks like nothing happened. But let's do some magic.
<?php
// First instance
$class1 = new SimpleClass;
$class1 instanceof \Delusion\PuppetThreadInterface; // true. Class has a new methods!
$class1->var; // 2
$class1->getVar(); // 2
$class1->delusionSetBehavior('getVar', 'a new value');
$class1->var; // 2
$class1->getVar(); // 'a new value'
$class2 = new SimpleClass(3);
$class2->var; // 3
$class2->getVar(); // 3
The var
in first class is 2, but method returns a string which we set by delusionSetBehavior()
method. The second class works as designed.
Just add Delusion project to require
or require-dev
section in your composer.json and do update.
{
"require-dev": {
"komex/delusion": "dev-develop"
}
}
Now you can do anything with all objects in your project.
This project was founded by Andrey Kolchenko (@komex) in August of 2013.
Having trouble with Delusion? Contact andrey@kolchenko.me and we’ll help you in the short time.