skagarwal/reflection

测试任何类中的私有/保护方法/属性

1.0.5 2015-05-31 00:00 UTC

This package is auto-updated.

Last update: 2024-09-09 19:31:27 UTC


README

Build Status Latest Stable Version Total Downloads Latest Unstable Version License
使用任何测试包和 配置测试您的 私有/保护 方法/属性。

新功能:可以同时反射多个类。

用法

步骤 1:通过 Composer 安装

composer require skagarwal/reflection --dev

步骤 2:导入特性

在任何包的 TestClass 中导入 SKAgarwal\Reflection\ReflectableTrait。例如:PhpUnitPhpSpecLaracasts\Integrated

对于 PhpUnit

use SKAgarwal\Reflection\ReflectableTrait

class ModelTest extends PHPUnit_Framework_TestCase
{
  use ReflectableTrait;
}

就这样。你已经准备就绪了。 :)

现在你可以执行以下操作来测试私有/保护方法或属性

实例化反射器

使用如下 reflect() 方法

$randomClass = new RandomClass();
$this->reflect($randomClass);

此方法不支持链式调用
注意:建议在 constructor 或对于 PhpUnit 的 setUp() 方法等中使用此方法。

使用 on() 方法如下

$randomClass = new RandomClass();
$this->on($randomClass)->call($method, $args = []);

此方法支持链式调用 **注意:**此方法仅对类对象进行一次反射。也就是说,它仅用于一次方法或属性的调用。它可以用于同时反射多个类。

可用方法

reflect($classObj);

描述:反射类对象

on($classObj);

描述:反射类对象。这是一个链式调用方法。
可能的链式调用

$this->on($classObject)->callMethod($arguments = []);
$this->on($classObject)->call($method, $arguments = []);
$this->on($classObject)->get($property);
$this->on($classObject)->get{Proerty};


#### call($method, $arguments = []); **描述:** 调用反射类对象的任何有效公共/私有/保护方法。这不是链式调用方法。

#### call{Method}($arguments = []); **描述:** 与 `call()` 相同,但动态调用方法。这不是链式调用方法。
{method} 可以是反射类对象的任何有效公共/私有/保护方法。

#### get($property); **描述:** 获取反射类对象的任何有效公共/私有/保护属性的值。这不是链式调用方法。

#### get{Property}; **描述:** 与 `get()` 相同,但动态获取属性的值。这不是链式调用方法。
{property} 可以是反射类对象的任何有效公共/私有/保护属性。

#### set($name, $value); **描述:** 设置反射类对象的任何有效公共/私有/保护属性的值。这不是链式调用方法。

#### set{Property} = $value; **描述:** 与 `set()` 相同,但动态设置属性的值。这不是链式调用方法。
{property} 可以是反射类对象的任何有效公共/私有/保护属性。

同时反射多个类

示例

// Considering phpunit

 protected function setUp()
  {
    $this->foo = new Foo();
    $this->reflect($this->foo);
  }
  

  public function test_something()
  {
    $hello = $this->callSayHello(); // this will call SayHello() of class `Foo`
    $this->assertEquals('Hello', $hello);

    $hello = $this->on(new FooBar())->callSayHello(); // this will call SayHello() of class `FooBar`
    $this->assertEquals('Hello FooBar', $hello);

    $hello = $this->callSayHello(); // this will call SayHello() of class `Foo`
    $this->assertEquals('Hello', $hello);
  }