Example #1
0
 /**
  * test::double registers class or object to track its calls.
  * In second argument you may pass values that mocked mathods should return.
  *
  * Returns either of [**ClassProxy**](https://github.com/Codeception/AspectMock/blob/master/docs/ClassProxy.md)
  * or [**InstanceProxy**](https://github.com/Codeception/AspectMock/blob/master/docs/InstanceProxy.md).
  * Proxies are used to verify method invocations, and some other useful things.
  *
  * Example:
  *
  * ``` php
  * <?php
  *
  * # simple
  * $user = test::double(new User, ['getName' => 'davert']);
  * $user->getName() // => davert
  * $user->verifyInvoked('getName'); // => success
  *
  * # with closure
  * $user = test::double(new User, ['getName' => function() { return $this->login; }]);
  * $user->login = '******';
  * $user->getName(); // => davert
  *
  * # on a class
  * $ar = test::double('ActiveRecord', ['save' => null]);
  * $user = new User;
  * $user->name = 'davert';
  * $user->save(); // passes to ActiveRecord->save() and does not insert any SQL.
  * $ar->verifyInvoked('save'); // true
  *
  * # on static method call
  * User::tableName(); // 'users'
  * $user = test::double('User', ['tableName' => 'fake_users']);
  * User::tableName(); // 'fake_users'
  * $user->verifyInvoked('tableName'); // success
  *
  * # append declaration
  * $user = new User;
  * test::double($user, ['getName' => 'davert']);
  * test::double($user, ['getEmail' => '*****@*****.**']);
  * $user->getName(); // => 'davert'
  * $user->getEmail(); => '*****@*****.**'
  *
  * # create an instance of mocked class
  * test::double('User')->construct(['name' => 'davert']); // via constructir
  * test::double('User')->make(); // without calling constructor
  * 
  * # stub for magic method
  * test::double('User', ['findByUsernameAndPasswordAndEmail' => false]);
  * User::findByUsernameAndPasswordAndEmail; // null
  * 
  * # stub for method of parent class
  * # if User extends ActiveRecord
  *
  * test::double('ActiveRecord', ['save' => false]);
  * $user = new User(['name' => 'davert']);
  * $user->save(); // false
  *
  * ?>
  * ```
  *
  * @api
  * @param $classOrObject
  * @param array $params
  * @throws \Exception
  * @return Proxy\ClassProxy|null
  */
 public static function double($classOrObject, $params = array())
 {
     $classOrObject = Registry::getRealClassOrObject($classOrObject);
     if (is_string($classOrObject)) {
         if (!class_exists($classOrObject)) {
             throw new \Exception("Class {$classOrObject} not loaded.\nIf you want to test undefined class use 'test::spec' method");
         }
         if (!\class_exists($classOrObject)) {
             $classOrObject = Registry::getNamespace() . '\\' . $classOrObject;
         }
         Core\Registry::registerClass($classOrObject, $params);
         return new Proxy\ClassProxy($classOrObject);
     }
 }