webxid/phpunitsandbox

此包帮助创建单元测试的模拟

0.3.0 2022-02-04 15:28 UTC

This package is auto-updated.

Last update: 2024-09-04 21:35:30 UTC


README

此包帮助在PHP v5.4 - 8.x版本中进行单元测试的模拟

源代码 https://github.com/webxid/PHPUnitSandbox

安装

PHPUnitSandbox不需要任何特殊的安装。

要求

  • PHP v5.4或更高版本
  • PHPUnitSandbox必须直接包含(不支持自动加载器,包括Composer)
  • PHP配置必须支持函数exec()eval()

安装步骤

  1. 运行composer require webxid/phpunitsandbox
  2. 如果您有任何,请注册额外的自动加载器
UnitSandbox::init([
        __DIR__ . '/../autoloader_1.php', // it has to be absolute route of autoloader file, and it has to be .php file
        ...
        __DIR__ . '/../autoloader_n.php',
    ])
    ->registerAutoloader();

!!! 重要 !!! 为了让沙箱正确工作,所有自动加载器都必须通过UnitSandbox注册,否则您将收到失败。同时,请检查./bootstrap.php

如何使用

此库作为沙箱工作

  • 首先,您设置一个类的模拟及其方法。
  • 然后,您调用UnitSandbox::execute(function() {});并将模拟的类传递到function() {}内部。

示例

// Setup a mock up of a class `DB` and of the static method `DB::query()`
UnitSandbox::mockClass('DB')
    ->mockStaticMethod('query', UnitSandbox::SELF_INSTANCE); //return self instance

// Then call the mocked method inside sandbox
$result = UnitSandbox::execute(function () {
    return \DB::query();
});

代码示例

模拟静态方法和对象方法

UnitSandbox::mockClass('DB')
    ->mockStaticMethod('query', UnitSandbox::SELF_INSTANCE) // returns self instance
    ->mockMethod('execute', [1,2,3]); // returns array(1,2,3)

模拟的类也可以在另一个类中使用

// This class should be able by autoloader
class TestClass
{
    public static function init()
    {
        return DB::query() // the usage of the mocked class
            ->execute();
    }
}
// Get result of TestClass::init();
$result = UnitSandbox::execute(function () {
    return \TestClass::init();
});

echo json_encode($result); // returns `[1,2,3]` 

间谍类

间谍类用于模拟类的部分。

  1. 例如,我们需要一个TestClass
class TestClass
{
    private static $my_property = 'Hello world!';

    public static function getProperty()
    {
        return static::$my_property;
    }
}
  1. 让我们重新编写TestClass的私有属性;
UnitSandbox::spyClass('\TestClass')
    ->defineStaticProperty('my_property', 'value');

$result_private_property = UnitSandbox::execute(function () {
    return \Spy\TestClass::getProperty();
});

echo $result_private_property; // it'll prints `value` instead `Hello world!`


*请参阅./tests/ExampleUnitTest.php中的所有示例* *

问题

要查看沙箱内部发生的错误,需要设置调试模式

UnitSandbox::init()
   ->debugMode(true, false);

许可证

PHPUnitSandbox采用Apache v2.0许可证。

版本日志

v0.3

  • 创建composer库
  • 小修复

v0.2

  • 模拟类属性定义
  • 传递参数到模拟方法
  • 间谍类逻辑
  • 小修复

v0.1

  • 方法模拟功能