Skip to content

反射模块测试 ​

本指南介绍如何测试 Kuiper 反射模块的功能,包括类型解析测试、PHPDoc 解析测试和类型过滤器测试。

测试概述 ​

反射模块测试主要包括:

  1. 类型解析测试 - 验证各种类型的解析和验证
  2. PHPDoc 解析测试 - 测试 PHPDoc 注解的解析
  3. 类型过滤器测试 - 验证类型过滤器的功能
  4. 集成测试 - 测试反射模块与其他组件的集成

测试环境设置 ​

基本测试类 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;
use kuiper\reflection\ReflectionDocBlockFactory;

class ReflectionTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        // 测试初始化
    }

    protected function tearDown(): void
    {
        parent::tearDown();
        // 清理资源
    }
}

类型解析测试 ​

基本类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class PrimitiveTypeTest extends TestCase
{
    public function testParseInteger(): void
    {
        $type = ReflectionType::parse('int');

        $this->assertSame('int', $type->getName());
        $this->assertTrue($type->isPrimitive());
        $this->assertTrue($type->isScalar());
        $this->assertFalse($type->allowsNull());
    }

    public function testParseString(): void
    {
        $type = ReflectionType::parse('string');

        $this->assertSame('string', $type->getName());
        $this->assertTrue($type->isPrimitive());
        $this->assertTrue($type->isScalar());
    }

    public function testParseFloat(): void
    {
        $type = ReflectionType::parse('float');

        $this->assertSame('float', $type->getName());
        $this->assertTrue($type->isPrimitive());
        $this->assertTrue($type->isScalar());
    }

    public function testParseBoolean(): void
    {
        $type = ReflectionType::parse('bool');

        $this->assertSame('bool', $type->getName());
        $this->assertTrue($type->isPrimitive());
        $this->assertTrue($type->isScalar());
    }

    public function testNullType(): void
    {
        $type = ReflectionType::parse('null');

        $this->assertSame('null', $type->getName());
        $this->assertTrue($type->isNull());
        $this->assertTrue($type->isPseudo());
    }
}

可空类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class NullableTypeTest extends TestCase
{
    public function testNullableWithQuestionMark(): void
    {
        $type = ReflectionType::parse('?int');

        $this->assertSame('int', $type->getName());
        $this->assertTrue($type->allowsNull());
        $this->assertSame('?int', (string) $type);
    }

    public function testNullableWithUnion(): void
    {
        $type = ReflectionType::parse('int|null');

        $this->assertSame('int|null', $type->getName());
        $this->assertTrue($type->allowsNull());
        $this->assertTrue($type->isComposite());
    }

    public function testWithAllowsNull(): void
    {
        $type = ReflectionType::parse('string');
        $nullableType = $type->withAllowsNull(true);

        $this->assertTrue($nullableType->allowsNull());
        $this->assertSame('?string', (string) $nullableType);
    }

    public function testWithoutAllowsNull(): void
    {
        $type = ReflectionType::parse('?string');
        $nonNullType = $type->withAllowsNull(false);

        $this->assertFalse($nonNullType->allowsNull());
        $this->assertSame('string', (string) $nonNullType);
    }
}

联合类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class CompositeTypeTest extends TestCase
{
    public function testParseUnionType(): void
    {
        $type = ReflectionType::parse('string|int|bool');

        $this->assertSame('string|int|bool', $type->getName());
        $this->assertTrue($type->isComposite());
    }

    public function testGetTypes(): void
    {
        $type = ReflectionType::parse('string|int|bool');
        $types = $type->getTypes();

        $this->assertCount(3, $types);
        $this->assertSame('string', $types[0]->getName());
        $this->assertSame('int', $types[1]->getName());
        $this->assertSame('bool', $types[2]->getName());
    }

    public function testContainsType(): void
    {
        $type = ReflectionType::parse('string|int|float');

        // CompositeType 未提供 containsType,需自行遍历 getTypes()
        $names = array_map(
            static fn ($item) => $item->getName(),
            $type->getTypes()
        );

        $this->assertContains('string', $names);
        $this->assertContains('int', $names);
        $this->assertContains('float', $names);
        $this->assertNotContains('bool', $names);
    }

    public function testNullableUnionType(): void
    {
        $type = ReflectionType::parse('string|int|null');

        $this->assertTrue($type->allowsNull());
        $this->assertTrue($type->isComposite());
    }
}

数组类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class ArrayTypeTest extends TestCase
{
    public function testParseSimpleArray(): void
    {
        $type = ReflectionType::parse('array');

        $this->assertSame('array', $type->getName());
        $this->assertTrue($type->isArray());
        $this->assertTrue($type->isUnknown());
    }

    public function testParseTypedArray(): void
    {
        $type = ReflectionType::parse('string[]');

        $this->assertTrue($type->isArray());
        $this->assertFalse($type->isUnknown());
        $this->assertSame('string', $type->getValueType()->getName());
    }

    public function testParseGenericArray(): void
    {
        $type = ReflectionType::parse('array<string>');

        $this->assertTrue($type->isArray());
        $this->assertSame('string', $type->getValueType()->getName());
    }

    public function testParseMapType(): void
    {
        $type = ReflectionType::parse('array<string, int>');

        $this->assertTrue($type->isArray());
        $this->assertSame('string', $type->getKeyType()->getName());
        $this->assertSame('int', $type->getValueType()->getName());
    }

    public function testParseMultiDimensionalArray(): void
    {
        $type = ReflectionType::parse('string[][]');

        $this->assertTrue($type->isArray());
        $this->assertSame(2, $type->getDimension());
    }

    public function testParseArrayShape(): void
    {
        $type = ReflectionType::parse('array{name: string, age: int}');

        $this->assertTrue($type->isArray());
        $this->assertCount(2, $type->getFields());
    }

    public function testParseArrayShapeWithOptional(): void
    {
        $type = ReflectionType::parse('array{name: string, age: ?int}');

        $this->assertTrue($type->isFieldOptional('age'));
        $this->assertFalse($type->isFieldOptional('name'));
    }
}

类类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class ClassTypeTest extends TestCase
{
    public function testParseClassType(): void
    {
        $type = ReflectionType::parse('DateTime');

        $this->assertSame('DateTime', $type->getName());
        $this->assertTrue($type->isClass());
        $this->assertTrue($type->isObject());
    }

    public function testParseNamespacedClass(): void
    {
        $type = ReflectionType::parse('App\\Models\\User');

        $this->assertSame('App\\Models\\User', $type->getName());
        $this->assertTrue($type->isClass());
    }

    public function testParseNullableClass(): void
    {
        $type = ReflectionType::parse('?DateTime');

        $this->assertTrue($type->allowsNull());
        $this->assertTrue($type->isClass());
    }
}

PHPDoc 解析测试 ​

方法文档块测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
use ReflectionMethod;

class PhpDocMethodTest extends TestCase
{
    private ReflectionDocBlockFactory $factory;

    protected function setUp(): void
    {
        parent::setUp();
        $this->factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
    }

    public function testParseMethodParameters(): void
    {
        $method = new ReflectionMethod(TestService::class, 'createUser');
        $docBlock = $this->factory->createMethodDocBlock($method);

        $nameType = $docBlock->getParameterTypes()['name'];
        $this->assertSame('string', $nameType->getName());

        $ageType = $docBlock->getParameterTypes()['age'];
        $this->assertSame('int', $ageType->getName());
    }

    public function testParseMethodReturnType(): void
    {
        $method = new ReflectionMethod(TestService::class, 'findById');
        $docBlock = $this->factory->createMethodDocBlock($method);

        $returnType = $docBlock->getReturnType();
        $this->assertSame('?User', (string) $returnType);
        $this->assertTrue($returnType->allowsNull());
    }

    public function testParseGenericArrayType(): void
    {
        $method = new ReflectionMethod(TestService::class, 'getUsers');
        $docBlock = $this->factory->createMethodDocBlock($method);

        $returnType = $docBlock->getReturnType();
        $this->assertTrue($returnType->isArray());
        $this->assertSame('User', $returnType->getValueType()->getName());
    }

    public function testParseMapType(): void
    {
        $method = new ReflectionMethod(TestService::class, 'getUserMap');
        $docBlock = $this->factory->createMethodDocBlock($method);

        $returnType = $docBlock->getReturnType();
        $this->assertTrue($returnType->isArray());
        $this->assertSame('int', $returnType->getKeyType()->getName());
        $this->assertSame('User', $returnType->getValueType()->getName());
    }
}

/**
 * 测试服务类
 */
class TestService
{
    /**
     * 创建用户
     *
     * @param string $name 用户名
     * @param int $age 年龄
     * @return User
     */
    public function createUser(string $name, int $age): User
    {
        return new User();
    }

    /**
     * 根据用户 ID 查找用户
     *
     * @param int $userId 用户 ID
     * @return User|null
     */
    public function findById(int $userId): ?User
    {
        return null;
    }

    /**
     * 获取用户列表
     *
     * @return array<int, User>
     */
    public function getUsers(): array
    {
        return [];
    }

    /**
     * 获取用户映射
     *
     * @return array<int, User>
     */
    public function getUserMap(): array
    {
        return [];
    }
}

class User
{
}

属性文档块测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
use ReflectionProperty;

class PhpDocPropertyTest extends TestCase
{
    private ReflectionDocBlockFactory $factory;

    protected function setUp(): void
    {
        parent::setUp();
        $this->factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
    }

    public function testParsePropertyType(): void
    {
        $property = new ReflectionProperty(TestModel::class, 'name');
        $docBlock = $this->factory->createPropertyDocBlock($property);

        $type = $docBlock->getType();
        $this->assertSame('string', $type->getName());
    }

    public function testParsePropertyArrayType(): void
    {
        $property = new ReflectionProperty(TestModel::class, 'tags');
        $docBlock = $this->factory->createPropertyDocBlock($property);

        $type = $docBlock->getType();
        $this->assertTrue($type->isArray());
        $this->assertSame('string', $type->getValueType()->getName());
    }

    public function testParsePropertyMapType(): void
    {
        $property = new ReflectionProperty(TestModel::class, 'metadata');
        $docBlock = $this->factory->createPropertyDocBlock($property);

        $type = $docBlock->getType();
        $this->assertTrue($type->isArray());
        $this->assertSame('string', $type->getKeyType()->getName());
        $this->assertSame('mixed', $type->getValueType()->getName());
    }
}

/**
 * 测试模型类
 */
class TestModel
{
    /**
     * @var string
     */
    private string $name;

    /**
     * @var array<string>
     */
    private array $tags;

    /**
     * @var array<string, mixed>
     */
    private array $metadata;
}

类型过滤器测试 ​

基本类型验证测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class TypeValidationTest extends TestCase
{
    public function testStringValidation(): void
    {
        $type = ReflectionType::parse('string');

        $this->assertTrue($type->isValid('hello'));
        $this->assertFalse($type->isValid(123));
        $this->assertFalse($type->isValid(null));
    }

    public function testNullableStringValidation(): void
    {
        $type = ReflectionType::parse('?string');

        $this->assertTrue($type->isValid('hello'));
        $this->assertTrue($type->isValid(null));
        $this->assertFalse($type->isValid(123));
    }

    public function testIntegerValidation(): void
    {
        $type = ReflectionType::parse('int');

        $this->assertTrue($type->isValid(123));
        $this->assertTrue($type->isValid(0));
        $this->assertFalse($type->isValid('123'));
        $this->assertFalse($type->isValid(null));
    }

    public function testArrayValidation(): void
    {
        $type = ReflectionType::parse('array');

        $this->assertTrue($type->isValid([]));
        $this->assertTrue($type->isValid([1, 2, 3]));
        $this->assertFalse($type->isValid('not an array'));
    }

    public function testTypedArrayValidation(): void
    {
        $type = ReflectionType::parse('int[]');

        $this->assertTrue($type->isValid([1, 2, 3]));
        $this->assertFalse($type->isValid(['1', '2', '3']));
    }

    public function testUnionTypeValidation(): void
    {
        $type = ReflectionType::parse('string|int');

        $this->assertTrue($type->isValid('hello'));
        $this->assertTrue($type->isValid(123));
        $this->assertFalse($type->isValid([]));
    }
}

类型清理测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class TypeSanitizationTest extends TestCase
{
    public function testStringSanitization(): void
    {
        $type = ReflectionType::parse('string');

        $this->assertSame('hello', $type->sanitize('hello'));
        $this->assertSame('123', $type->sanitize(123));
    }

    public function testIntegerSanitization(): void
    {
        $type = ReflectionType::parse('int');

        $this->assertSame(123, $type->sanitize('123'));
        $this->assertSame(123, $type->sanitize(123.45));
    }

    public function testFloatSanitization(): void
    {
        $type = ReflectionType::parse('float');

        $this->assertSame(3.14, $type->sanitize('3.14'));
        $this->assertSame(3.0, $type->sanitize(3));
    }

    public function testBooleanSanitization(): void
    {
        $type = ReflectionType::parse('bool');

        $this->assertTrue($type->sanitize(1));
        $this->assertFalse($type->sanitize(0));
        $this->assertTrue($type->sanitize('true'));
    }

    public function testArraySanitization(): void
    {
        $type = ReflectionType::parse('array');

        $this->assertIsArray($type->sanitize('not an array'));
    }
}

从 PHP 反射创建类型测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;

class ReflectionTypeConversionTest extends TestCase
{
    public function testFromParameterType(): void
    {
        $method = new ReflectionMethod(ExampleClass::class, 'methodWithTypes');
        $parameters = $method->getParameters();

        // 第一个参数 string $name
        $nameType = ReflectionType::fromPhpType($parameters[0]->getType());
        $this->assertSame('string', $nameType->getName());

        // 第二个参数 ?int $count
        $countType = ReflectionType::fromPhpType($parameters[1]->getType());
        $this->assertSame('?int', (string) $countType);
        $this->assertTrue($countType->allowsNull());

        // 第三个参数 array|string $data
        $dataType = ReflectionType::fromPhpType($parameters[2]->getType());
        $this->assertSame('array|string', $dataType->getName());
    }

    public function testFromReturnType(): void
    {
        $method = new ReflectionMethod(ExampleClass::class, 'methodWithTypes');
        $returnType = ReflectionType::fromPhpType($method->getReturnType());

        $this->assertSame('array|false', $returnType->getName());
    }

    public function testFromPropertyType(): void
    {
        $property = new ReflectionProperty(ExampleClass::class, 'name');
        $propertyType = ReflectionType::fromPhpType($property->getType());

        $this->assertSame('string', $propertyType->getName());
    }

    public function testFromNullablePropertyType(): void
    {
        $property = new ReflectionProperty(ExampleClass::class, 'user');
        $propertyType = ReflectionType::fromPhpType($property->getType());

        $this->assertSame('?User', (string) $propertyType);
        $this->assertTrue($propertyType->allowsNull());
    }
}

/**
 * 示例类
 */
class ExampleClass
{
    private string $name;

    private ?User $user;

    /**
     * 示例方法
     *
     * @param string $name 名称
     * @param int|null $count 数量
     * @param array|string $data 数据
     * @return array|false
     */
    public function methodWithTypes(string $name, ?int $count, array|string $data): array|false
    {
        return [];
    }
}

class User
{
}

缓存测试 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
use ReflectionMethod;

class CacheTest extends TestCase
{
    public function testLruCache(): void
    {
        $factory = new ReflectionDocBlockFactory(10, new UseStatementCache());

        $method = new ReflectionMethod(CacheTestClass::class, 'testMethod');

        // 创建文档块(会被缓存)
        $docBlock1 = $factory->createMethodDocBlock($method);
        $docBlock2 = $factory->createMethodDocBlock($method);

        // 应该返回相同的实例(来自缓存)
        $this->assertSame($docBlock1, $docBlock2);

        // 检查缓存统计
        $stats = $factory->getCacheStats();
        $this->assertSame('lru', $stats['mode']);
        $this->assertSame(1, $stats['size']);
    }

    public function testCacheClear(): void
    {
        $factory = new ReflectionDocBlockFactory(100, new UseStatementCache());

        $method = new ReflectionMethod(CacheTestClass::class, 'testMethod');
        $factory->createMethodDocBlock($method);

        // 清除缓存
        $factory->clearCache();

        // 缓存应该为空
        $stats = $factory->getCacheStats();
        $this->assertSame(0, $stats['size']);
    }
}

class CacheTestClass
{
    /**
     * 测试方法
     *
     * @param string $param 参数
     * @return void
     */
    public function testMethod(string $param): void
    {
    }
}

测试最佳实践 ​

1. 使用数据提供器 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class TypeParsingDataProviderTest extends TestCase
{
    /**
     * @return array<array{string, string}>
     */
    public static function primitiveTypeProvider(): array
    {
        return [
            ['int', 'int'],
            ['string', 'string'],
            ['float', 'float'],
            ['bool', 'bool'],
            ['null', 'null'],
        ];
    }

    /**
     * @dataProvider primitiveTypeProvider
     */
    public function testParsePrimitiveTypes(string $input, string $expectedName): void
    {
        $type = ReflectionType::parse($input);

        $this->assertSame($expectedName, $type->getName());
        $this->assertTrue($type->isPrimitive());
    }
}

2. 测试异常情况 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\ReflectionType;

class ExceptionTest extends TestCase
{
    public function testParseEmptyString(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Type string cannot be empty');

        ReflectionType::parse('');
    }

    public function testParseInvalidType(): void
    {
        // 解析器会尽量解析,不会抛出异常
        // 而是返回一个 mixed 类型
        $type = ReflectionType::parse('InvalidClassName');

        $this->assertSame('InvalidClassName', $type->getName());
    }
}

3. 使用 Mock 对象 ​

php
<?php

declare(strict_types=1);

namespace Tests\reflection;

use PHPUnit\Framework\TestCase;
use kuiper\reflection\parser\PhpstanTypeParser;
use kuiper\reflection\TypeParserInterface;
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\reflection\ReflectionType;

class CustomParserTest extends TestCase
{
    public function testSetCustomParser(): void
    {
        // 创建 Mock 解析器
        // 注意:不要在自定义解析器里回调 ReflectionType::parse(),否则会无限递归
        $mockParser = $this->createMock(TypeParserInterface::class);
        $mockParser->method('parse')
            ->willReturnCallback(function (string $typeString) {
                return (new PhpstanTypeParser())->parse($typeString);
            });

        // 设置自定义解析器
        ReflectionType::setParser($mockParser);

        // 测试解析
        $type = ReflectionType::parse('string');
        $this->assertSame('string', $type->getName());

        // 恢复默认解析器(setParser 的参数不可为 null)
        ReflectionType::setParser(new PhpstanTypeParser());
    }
}

运行测试 ​

运行所有反射测试 ​

bash
# 运行所有反射测试
./vendor/bin/phpunit tests/reflection

# 运行特定测试文件
./vendor/bin/phpunit tests/reflection/ReflectionTypeTest.php

# 运行特定测试方法
./vendor/bin/phpunit --filter testParseString tests/reflection/ReflectionTypeTest.php

# 生成代码覆盖率报告
./vendor/bin/phpunit --coverage-html coverage/ tests/reflection

更多资源 ​

基于 MIT 许可发布