alphametric/reflection-assertions

该包已被弃用,不再维护。未建议替代包。

一个包,用于启用测试对象的私有和受保护属性和方法。

v1.0 2018-10-29 15:43 UTC

This package is auto-updated.

Last update: 2020-02-17 10:07:52 UTC


README

该包为 Laravel 的 TestCase 或通用 PHP TestCase 中的 $this 添加了一组基于反射的断言。它还添加了几个方法,允许直接访问任何对象的私有和受保护属性和方法。您可以使用这些方法绕过 PHP 的作用域限制,并完全单元测试您的类。

安装

您可以通过 composer 安装此包

composer require alphametric/reflection-assertions

包安装完成后,您需要将 ReflectionAssertions 特性添加到 TestCase 类中

namespace Tests;

use Alphametric\Assertions\ReflectionAssertions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication, ReflectionAssertions;
}

使用

如果您想直接访问对象上的属性或方法,可以使用专用函数

名称 参数
getProperty $property_name, $object_instance
setProperty $property_name, $object_instance, $new_value
callFunction $function_name, $object_instance, $function_parameters[]
$object = new MailMessage();

$this -> getProperty("bcc_address", $object);
$this -> setProperty("bcc_address", $object, "john@example.com");

$this -> callFunction("getBcc", $object);
$this -> callFunction("removeCC", $object, ["john@example.com"]);
$this -> callFunction("internalSend", $object, ["john@example.com", "Hello John!"]);

断言

每个专用函数也作为传统断言提供

$this -> assertFunctionReturns();

由于所有断言都返回类实例,因此您还可以链式调用多个断言

$this -> assertPropertyIs()
      -> assertFunctionReturns()
      -> assertPropertyIs();

以下断言可用于使用

名称 参数
assertFunctionReturns $expected_value, $function_name, $object_instance, $function_parameters[]
assertFunctionDoesNotReturn $expected_value, $function_name, $object_instance, $function_parameters[]
assertPropertyIs $expected_value, $property_name, $object_instance
assertPropertyIsNot $expected_value, $property_name, $object_instance
$this -> assertFunctionReturns(1, "privateMethod", $object);
$this -> assertFunctionDoesNotReturn(2, "protectedMethod", $object, ["param_1", "param_2"]);
$this -> assertPropertyIs("John", "privateProperty", $object);
$this -> assertPropertyIsNot("Alex", "protectedProperty", $object);

由于 setProperty 方法在调用并返回 getProperty 方法后结束,因此您可以利用两个额外的断言来验证对象属性的变化。这对于 Laravel 的访问器/修改器非常有用

名称 参数
assertPropertyWhenSetIs $expected_value, $property_name, $object_instance, $new_value
assertPropertyWhenSetIsNot $expected_value, $property_name, $object_instance, $new_value
$this -> assertPropertyWhenSetIs("Mr. Alex", "privateProperty", $object, "Alex");
$this -> assertPropertyWhenSetIsNot("Ms. Jane", "protectedProperty", $object, "Jane");

测试

您可以通过在包根目录下使用以下命令来运行测试套件

composer test

变更日志

V1.0 - 初次发布。

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件