Skip to content

工具模块测试 ​

测试概述 ​

kuiper/helper 是纯工具库,没有容器与运行环境依赖,测试就是普通的 PHPUnit 单元测试:构造输入、调用静态方法或 Config 实例、断言输出。框架自身对每个工具都有完整测试覆盖(helper/tests/),业务项目一般不需要为 helper 本身写测试——需要测试的是业务代码对工具的使用。

测试 Config ​

点路径读写 ​

php
<?php

declare(strict_types=1);

namespace App\Tests;

use kuiper\helper\Config;
use PHPUnit\Framework\TestCase;

class MyConfigTest extends TestCase
{
    public function testDotNotationAccess(): void
    {
        $config = Config::create([
            'application' => [
                'database' => ['host' => 'localhost'],
            ],
        ]);

        $this->assertSame('localhost', $config->get('application.database.host'));
        $this->assertSame('db', $config->get('application.missing.host', 'db'));
        $this->assertTrue($config->has('application.database.host'));
    }
}

合并策略 ​

三种合并方法语义不同(见配置指南),混用前值得为业务配置的叠加顺序写用例:

php
<?php

declare(strict_types=1);

use kuiper\helper\Config;
use PHPUnit\Framework\TestCase;

class ConfigMergeTest extends TestCase
{
    public function testReplaceOverwritesScalarsButKeepsUnmentionedKeys(): void
    {
        $config = Config::create(['logging' => ['level' => 'info', 'path' => '/tmp']]);
        $config->replace(['logging' => ['level' => 'debug']]);

        $this->assertSame('debug', $config->get('logging.level'));
        $this->assertSame('/tmp', $config->get('logging.path'));
    }

    public function testMergeAppendsIndexArrays(): void
    {
        $config = Config::create(['tags' => ['a']]);
        $config->merge(['tags' => ['b']]);

        $this->assertSame(['a', 'b'], $config->get('tags'));
    }

    public function testMergeWhenAbsentKeepsExistingKeys(): void
    {
        $config = Config::create(['level' => 'info']);
        $config->mergeWhenAbsent(['level' => 'debug']);

        $this->assertSame('info', $config->get('level'));
    }
}

占位符 ​

php
<?php

declare(strict_types=1);

use kuiper\helper\Config;
use PHPUnit\Framework\TestCase;

class ConfigPlaceholderTest extends TestCase
{
    public function testPlaceholderResolvesFromOtherEntries(): void
    {
        $config = Config::create([
            'name' => 'myapp',
            'file' => '{name}.log',
        ]);
        $config->replacePlaceholder();

        $this->assertSame('myapp.log', $config->get('file'));
    }

    public function testCircularReferenceThrows(): void
    {
        $config = Config::create(['a' => '{b}', 'b' => '{a}']);

        $this->expectException(\InvalidArgumentException::class);
        $config->replacePlaceholder();
    }
}

测试 env() / env_bool() ​

env() 按 $_ENV → $_SERVER → getenv() 顺序取值,测试里直接操作 $_ENV 即可控制输入(记得清理,避免污染同进程的其他测试):

php
<?php

declare(strict_types=1);

use function kuiper\helper\env;
use function kuiper\helper\env_bool;
use PHPUnit\Framework\TestCase;

class EnvFunctionTest extends TestCase
{
    protected function setUp(): void
    {
        unset($_ENV['MY_FEATURE']);
    }

    protected function tearDown(): void
    {
        unset($_ENV['MY_FEATURE']);
    }

    public function testReturnsStringWhenSet(): void
    {
        $_ENV['MY_FEATURE'] = '1';

        $this->assertSame('1', env('MY_FEATURE', false));
    }

    public function testKeepsDefaultTypeWhenUnset(): void
    {
        $this->assertFalse(env('MY_FEATURE', false));
        $this->assertSame(0, env('MY_FEATURE', 0));
    }

    public function testEnvBoolParsesLiterals(): void
    {
        $_ENV['MY_FEATURE'] = 'yes';

        $this->assertTrue(env_bool('MY_FEATURE'));
    }

    public function testEnvBoolRejectsInvalidValues(): void
    {
        $_ENV['MY_FEATURE'] = 'enable';

        $this->expectException(\InvalidArgumentException::class);
        env_bool('MY_FEATURE');
    }
}

env_bool() 的严格语义是它存在的意义:'false'、'off'、空字符串解析为 false,'enable' 这类非法字面量抛异常而不是当成 true。

测试 Arrays / Text / EnumHelper ​

纯静态方法,直接调用即可。业务测试的重点是字段名与真实数据结构的对齐:

php
<?php

declare(strict_types=1);

use kuiper\helper\Arrays;
use kuiper\helper\EnumHelper;
use PHPUnit\Framework\TestCase;

class HelperUsageTest extends TestCase
{
    public function testGroupUsersByDept(): void
    {
        // 注意:groupByField 只读对象属性(is_object($elem) && isset($elem->$field)),
        // 元素是数组时会落成空键 '',这种情况请改用 Arrays::groupBy()
        $users = [
            new User(dept: 'eng', name: 'alice'),
            new User(dept: 'ops', name: 'carol'),
        ];

        $grouped = Arrays::groupByField($users, 'dept');

        $this->assertSame(['eng', 'ops'], array_keys($grouped));
        $this->assertSame('carol', $grouped['ops'][0]->name);
    }

    public function testEnumFromBackingValue(): void
    {
        $this->assertNull(EnumHelper::tryFrom(MyStatus::class, 'gone'));
    }
}

final class User
{
    public function __construct(
        public readonly string $dept,
        public readonly string $name,
    ) {
    }
}

测试业务配置读取 ​

业务服务通过 ConfigAwareTrait 或构造函数注入 ConfigInterface 读取配置。测试时用 Config::create() 构造与 src/config.php 相同结构的配置:

php
<?php

declare(strict_types=1);

use kuiper\helper\Config;
use PHPUnit\Framework\TestCase;

class PricingServiceTest extends TestCase
{
    public function testReadsTaxRateFromConfig(): void
    {
        $service = new PricingService();
        $service->setConfig(Config::create([
            'application' => ['tax' => ['rate' => 0.13]],
        ]));

        $this->assertSame(0.13, $service->taxRate());
    }
}

测试最佳实践 ​

1. 测试结束清理 $_ENV ​

env() / env_bool() 读的是进程级全局状态,setUp() / tearDown() 里 unset 掉测试写入的键,避免影响同进程其他测试。

2. 不要为工具本身重复造测试 ​

Config 强转语义、Arrays 边界行为等已由 helper/tests/ 覆盖(如 ConfigCastSemanticsTest)。业务测试聚焦「传给工具的数据长什么样、期望得到什么」。

3. 配置结构用真实结构 ​

构造测试配置时保持与 src/config.php 一致的嵌套结构,否则点路径断言会给出虚假的安全感。

下一步 ​

基于 MIT 许可发布