chadicus/test-helpers

用于协助PHPUnit测试的类

v3.0.0 2023-07-05 15:00 UTC

This package is auto-updated.

Last update: 2024-09-05 17:28:28 UTC


README

Latest Stable Version Latest Unstable Version License

Total Downloads Daily Downloads Monthly Downloads

要求

Test Helpers 需要 PHP 7.3(或更高版本)。

Composer

要作为本地、项目级别的依赖项添加库,请使用 Composer!只需将 chadicus/test-helpers 作为依赖项添加到您的项目 composer.json 文件中,例如

composer require --dev chadicus/test-helpers

注意:test-helpers 不应在生产环境中使用。它们仅适用于测试环境。

文档

项目的PHP文档可以在这里找到。

联系方式

开发者可以通过以下方式联系

项目构建

通过检出代码,在您的PATH中获取 Composer 并运行

composer install
composer run test
composer run lint

\Chadicus\FunctionRegistry

某些内部PHP函数在失败时被记录为返回特定值。如果您是一位细致的程序员,您希望在代码中考虑到这些返回值并相应地做出反应。

class MyClass
{
    public function doSomething()
    {
        $curl = curl_init();
        if ($curl === false) {
            throw new \Exception('curl_init() failed');
        }

        //do something with $curl ...
    }
}

细致的程序员还可能希望确保他们的单元测试代码覆盖率是100%。

实现这一点的一种方法是通过使用 @codeCoverageIgnore 注解

class MyClass
{
    public function doSomething()
    {
        $curl = curl_init();
        if ($curl === false) {
            //@codeCoverageIgnoreStart
            throw new \Exception('curl_init() failed');
            //@codeCoverageIgnoreEnd
        }

        //do something with $curl ...
    }
}

这为我们提供了代码覆盖率,但代码实际上并没有被测试。

FunctionRegistry 类允许您 模拟 内部PHP函数

class MyClassTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        // prepare the curl functions for mocking
        \Chadicus\FunctionRegistry::reset(__NAMESPACE__, array('curl'));
    }

    /**
     * @expectedExceptionMessage curl_init() failed
     */
    public function testCurlInitFails()
    {
        \Chadicus\FunctionRegistry::set(
            __NAMESPACE__,
            'curl_init',
            function () {
                return false;
            }
        );

        $myClass = new MyClass();

        // this will call our custom curl_init function
        $myClass->doSomething();
    }
}

对于函数和常量,如果命名空间中的函数或常量不存在,PHP将回退到全局函数或常量。正是由于这种行为,我们可以 模拟 内部函数。