Skip to content

序列化模块测试 ​

测试思路 ​

序列化模块的测试全部是纯内存的:Serializer 不依赖数据库或网络,构造时 注入的 ClassMetadataFactory / normalizer 都可以替换成测试替身。

三块内容值得分别测:

  • 序列化 / 反序列化语义:标量、数组、对象、联合类型、DateTime、枚举;
  • 类型校验与异常:非法 JSON、类型不匹配、递归深度、JSON 体积上限;
  • 安全配置:白名单(严格模式)与危险类黑名单;
  • 元数据缓存:ClassMetadataFactory 的持久缓存命中与失效。

框架自身测试在 serializer/tests/(SerializerTest、 SerializerComprehensiveTest、ClassMetadataFactoryCacheTest、 normalizer/PhpEnumNormalizerTest 等),可直接照搬。

构造测试用的 Serializer ​

Serializer 构造函数签名:

text
__construct(
    ?ClassMetadataFactory $classMetadataFactory = null,
    array $normalizers = [],
    ?CompiledTypeValidator $typeValidator = null,
    array $allowedClasses = [],
)

不传 ClassMetadataFactory 时会创建默认实例(带反射工厂,无持久缓存)。 DateTime / 枚举等内建 normalizer 不会自动注册,需要显式传入:

php
<?php

declare(strict_types=1);

namespace App\Tests\Serializer;

use kuiper\serializer\Serializer;
use kuiper\serializer\normalizer\DateTimeNormalizer;
use kuiper\serializer\normalizer\ExceptionNormalizer;
use kuiper\serializer\normalizer\PhpEnumNormalizer;
use PHPUnit\Framework\TestCase;

class UserDtoTest extends TestCase
{
    private Serializer $serializer;

    protected function setUp(): void
    {
        $this->serializer = new Serializer(
            normalizers: [
                \DateTimeInterface::class => new DateTimeNormalizer(),
                \Exception::class => new ExceptionNormalizer(),
                \UnitEnum::class => new PhpEnumNormalizer(),
            ],
        );
    }
}

裸 new Serializer() 不带 built-in normalizer

与容器里 SerializerConfiguration 注册的默认 normalizer 集合不同,手写的 new Serializer() 只有第二个参数传入的 normalizer。DateTime 不传 DateTimeNormalizer 时会被 ObjectNormalizer 按 getter 展开,而不是输出 RFC3339 字符串——测试里要断言日期格式时务必显式注册。

测试序列化与反序列化 ​

对象先在 PHP 侧构造,用 normalize() / toJson() 断言输出;反过来用 denormalize() / fromJson() 断言还原:

php
final class UserDto
{
    public function __construct(private string $name, private int $age)
    {
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getAge(): int
    {
        return $this->age;
    }

    public function setName(string $name): void
    {
        $this->name = $name;
    }

    public function setAge(int $age): void
    {
        $this->age = $age;
    }
}

public function testRoundTrip(): void
{
    $json = $this->serializer->toJson(new UserDto('Alice', 30));
    $this->assertSame('{"name":"Alice","age":30}', $json);

    $back = $this->serializer->fromJson('{"name":"Bob","age":25}', UserDto::class);
    $this->assertInstanceOf(UserDto::class, $back);
    $this->assertSame('Bob', $back->getName());
    $this->assertSame(25, $back->getAge());
}

public function testDateTimeUsesRfc3339(): void
{
    $date = new \DateTime('2024-01-01 12:00:00', new \DateTimeZone('UTC'));

    $this->assertSame(
        '2024-01-01T12:00:00+00:00',
        $this->serializer->normalize($date)
    );
}

数组与 JSON 的边界也要覆盖:toJson([]) 是 "[]",toJson(['name' => 'Alice']) 解码后与输入一致(assertJson() / json_decode(..., true) 对比)。 denormalize() 的第三个形态是类型对象: ReflectionType::parse(UserDto::class) 与传类名字符串等价,fromJson() 也接受 new UserDto(...) 这样的纯对象作为类型参数。

测试异常与类型校验 ​

序列化异常都继承 kuiper\serializer\exception\SerializeException,具体子类 区分场景:

异常触发场景
MalformedJsonException空字符串、超过 10MB(MAX_JSON_SIZE)、非法 JSON
TypeException反序列化类型不匹配(如 null 赋给 string、'x' 赋给 array)
NotSerializableException类中存在无法序列化的方法或属性(ClassMetadataFactory 构建元数据时抛出)
SerializeException(基类)toJson 编码失败、递归超过 256 层(MAX_RECURSION_DEPTH)
php
use kuiper\serializer\exception\MalformedJsonException;
use kuiper\serializer\exception\SerializeException;
use kuiper\serializer\exception\TypeException;

public function testEmptyJsonThrows(): void
{
    $this->expectException(MalformedJsonException::class);
    $this->expectExceptionMessage('JSON string cannot be empty');
    $this->serializer->fromJson('', 'string');
}

public function testInvalidJsonThrows(): void
{
    $this->expectException(MalformedJsonException::class);
    $this->serializer->fromJson('{invalid json}', 'array');
}

public function testTypeMismatchThrows(): void
{
    $this->expectException(TypeException::class);
    $this->expectExceptionMessage('does not allow null value');
    $this->serializer->denormalize(null, 'string');
}

public function testExcessiveRecursionThrows(): void
{
    // 构造超过 MAX_RECURSION_DEPTH (256) 的嵌套数组
    $data = [];
    $current = &$data;
    for ($i = 0; $i < 300; ++$i) {
        $current['nested'] = [];
        $current = &$current['nested'];
    }

    $this->expectException(SerializeException::class);
    $this->expectExceptionMessage('Maximum recursion depth');
    $this->serializer->normalize($data);
}

测试自定义 Normalizer ​

自定义 normalizer 实现 NormalizerInterface(normalize() + denormalize()),按类名注册进第二个参数;匹配规则是 is_a($className, $typeClass, true),所以父类 / 接口键也能命中:

php
use kuiper\reflection\ReflectionTypeInterface;
use kuiper\serializer\NormalizerInterface;

final class UpperTokenNormalizer implements NormalizerInterface
{
    public function normalize(mixed $object): mixed
    {
        return strtoupper($object->raw);
    }

    public function denormalize(mixed $data, string|ReflectionTypeInterface $className): mixed
    {
        return new Token(strtolower((string) $data));
    }
}

public function testCustomNormalizer(): void
{
    $serializer = new Serializer(normalizers: [Token::class => new UpperTokenNormalizer()]);

    $this->assertSame('ABC', $serializer->normalize(new Token('abc')));
    $this->assertSame('xyz', $serializer->denormalize('XYZ', Token::class)->raw);
}

注册顺序决定匹配结果

normalizers 按数组顺序逐项 instanceof 匹配。同时注册 \DateTimeInterface 与 \DateTime 时,先命中的那个生效;测试自定义 normalizer 时用具体类而不是 父接口做键,避免与内建 normalizer 抢匹配。

测试白名单与危险类黑名单 ​

「非空白名单即严格模式」:Serializer 的第 4 个参数传入允许的类,此时只允许 白名单(含 App\Entity\* 这类命名空间通配符)中的类反序列化:

php
public function testWhitelistRejectsUnknownClass(): void
{
    // 只允许 UserDto,其余类一律拒绝
    $serializer = new Serializer(
        null,
        [\DateTimeInterface::class => new DateTimeNormalizer()],
        null,
        [UserDto::class],
    );

    $this->assertInstanceOf(UserDto::class, $serializer->fromJson('{"name":"A","age":1}', UserDto::class));

    $this->expectException(SerializeException::class);
    $this->expectExceptionMessage('not in the deserialization whitelist');
    $serializer->fromJson('{}', \DateTime::class);
}

public function testDangerousClassIsBlacklisted(): void
{
    // 白名单为空(非严格模式)时仍拦截已知危险类
    $serializer = new Serializer();

    $this->expectException(SerializeException::class);
    $this->expectExceptionMessage('blacklisted');
    $serializer->fromJson('{}', \ReflectionClass::class);
}

严格模式优先

配置了白名单后只检查白名单,不再检查黑名单;两者不是叠加关系。测试里要分别 用「带白名单」和「不带白名单」的两个 Serializer 实例覆盖这两条分支。

测试元数据缓存 ​

ClassMetadataFactory 构造函数签名:

text
__construct(
    ReflectionDocBlockFactoryInterface $reflectionDocBlockFactory,
    ?CacheItemPoolInterface $cache = null,   // 持久缓存(PSR-6)
    string $cacheKeyPrefix = 'class_metadata_',
)

PSR-6 持久缓存用框架自带的 kuiper\cache\stash\CacheItemPool + Ephemeral 驱动即可(无需 Redis),断言「清除内存缓存后从持久缓存读回」 与「损坏的暖缓存按 miss 重建」:

php
use kuiper\cache\stash\CacheItemPool;
use kuiper\cache\stash\driver\Ephemeral;
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
use kuiper\serializer\ClassMetadata;
use kuiper\serializer\ClassMetadataFactory;

public function testSecondFactoryReadsWarmCache(): void
{
    $cache = new CacheItemPool(new Ephemeral());
    $factory = new ClassMetadataFactory(
        new ReflectionDocBlockFactory(1000, new UseStatementCache()),
        $cache
    );

    $metadata1 = $factory->create(UserDto::class);

    // 新工厂实例:内存缓存为空,必须走持久缓存读取路径
    $metadata2 = (new ClassMetadataFactory(
        new ReflectionDocBlockFactory(1000, new UseStatementCache()),
        $cache
    ))->create(UserDto::class);

    $this->assertInstanceOf(ClassMetadata::class, $metadata2);
    $this->assertEquals($metadata1, $metadata2);
    $this->assertSame(UserDto::class, $metadata2->getClassName());
    $this->assertCount(2, $metadata2->getGetters());
}

public function testClearCacheForcesRebuild(): void
{
    $cache = new CacheItemPool(new Ephemeral());
    $factory = new ClassMetadataFactory(
        new ReflectionDocBlockFactory(1000, new UseStatementCache()),
        $cache
    );

    $metadata1 = $factory->create(UserDto::class);
    // 精确清除某个类,或 clearCache() 清空全部
    $factory->clearCache(UserDto::class);
    $metadata2 = $factory->create(UserDto::class);

    $this->assertNotSame($metadata1, $metadata2);
}

不要用 clearCache 测暖缓存

clearCache() 会连持久缓存一起删,用它做「第二个工厂读暖缓存」的用例 会掩盖持久缓存路径的 bug。框架测试 testSecondFactoryReadsWarmCache 特意不调用 clearCache(),改由新建工厂 实例驱动持久缓存读取。

测试 Valinor 适配器 ​

cuyz/valinor 是可选依赖(suggest),未安装时跳过用例。测试时通过 SerializerConfiguration 构建容器,从容器取 ValinorSerializerAdapter:

php
use Composer\Autoload\ClassLoader;
use kuiper\di\ContainerBuilder;
use kuiper\helper\Config;
use kuiper\serializer\adapter\ValinorSerializerAdapter;
use kuiper\serializer\SerializerConfiguration;
use kuiper\serializer\exception\SerializeException;

public function testValinorAdapterMapsDto(): void
{
    $builder = new ContainerBuilder(new ClassLoader(), Config::create());
    $builder->addConfiguration(new SerializerConfiguration());
    $container = $builder->build();
    $adapter = $container->get(ValinorSerializerAdapter::class);

    $dto = $adapter->fromJson('{"name":"Alice"}', UserDto::class);
    $this->assertSame('Alice', $dto->getName());

    $this->expectException(SerializeException::class);
    $adapter->fromJson('{"age":"not-int"}', UserDto::class);
}

必须走容器的 MapperBuilder

SerializerConfiguration::valinorMapperBuilder() 会调用 MapperBuilder::allowPermissiveTypes()。直接 new MapperBuilder() 传给适配器, 对未标注具体类型的字段会抛 Valinor 的 CannotMapToPermissiveType。要么用容器 构建,要么自己显式调用 allowPermissiveTypes()。

适配器把所有 Valinor 映射错误统一包装为 SerializeException,原始异常在 getPrevious() 中(MappingError 时可迭代其 messages() 取出错误明细)。

测试最佳实践 ​

  • 纯内存:序列化测试不需要任何外部依赖,setUp() 里构造 Serializer 即可;
  • 显式注册 normalizer:DateTime / 枚举 / Exception 的行为取决于是否注册了 对应 normalizer,测试前先确认这一点;
  • 异常精确到子类:断言 MalformedJsonException / TypeException 而不是 宽泛的 \Exception,语义更准确;
  • 缓存的暖路径要单测:ClassMetadataFactory 的持久缓存重建路径曾因 __unserialize 重复赋值 readonly 属性直接 fatal,必须用「新建工厂读暖 缓存」的做法覆盖(参见 serializer/tests/ClassMetadataFactoryCacheTest.php)。

下一步 ​

基于 MIT 许可发布