定制 patchlevel/event-sourcing-phpunit 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

patchlevel/event-sourcing-phpunit

Composer 安装命令:

composer require --dev patchlevel/event-sourcing-phpunit

包简介

PHPUnit testing utilities for patchlevel/event-sourcing

README 文档

README

Mutation testing badge Latest Stable Version License

Testing utilities

With this library you can ease the testing for your event-sourcing project when using PHPUnit. It comes with utilities for aggregates and subscribers.

Installation

composer require --dev patchlevel/event-sourcing-phpunit

Testing Aggregates

There is a special TestCase for aggregate tests which you can extend from. Extending from AggregateRootTestCase enables you to use the given / when / then notation. This makes it very clear what the test is doing. When extending the class you will need to implement a method which provides the FQCN of the aggregate you want to test.

final class ProfileTest extends AggregateRootTestCase
{
    protected function aggregateClass(): string
    {
        return Profile::class;
    }
}

When this is done, you already can start testing your behaviour. For example testing that a event is recorded.

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->given(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
            )
            ->when(static fn (Profile $profile) => $profile->visitProfile(ProfileId::fromString('2')))
            ->then(new ProfileVisited(ProfileId::fromString('2')));
    }
}

You can also provide multiple given events and expect multiple events:

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->given(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
                new ProfileVisited(ProfileId::fromString('2')),
            )
            ->when(
                static function (Profile $profile) {
                    $profile->visitProfile(ProfileId::fromString('3'));
                    $profile->visitProfile(ProfileId::fromString('4'));
                }
            )
            ->then(
                new ProfileVisited(ProfileId::fromString('3')),
                new ProfileVisited(ProfileId::fromString('4')),
            );
    }
}

You can also test the creation of the aggregate:

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->when(static fn () => Profile::createProfile(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de')))
            ->then(new ProfileCreated(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de')));
    }
}

And expect an exception and the message of it:

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->given(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
            )
            ->when(static fn (Profile $profile) => $profile->throwException())
            ->expectsException(ProfileError::class)
            ->expectsExceptionMessage('throwing so that you can catch it!');
    }
}

Asserting aggregate state

You can pass closures to then() to assert on the aggregate's state after the events have been applied. This is useful when your aggregate exposes state via public properties or getters that are set in apply methods. Closures receive the aggregate instance and are executed after the event assertion. You can mix closures and expected events freely — event order is preserved regardless of callback placement.

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->given(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
            )
            ->when(static fn (Profile $profile) => $profile->visitProfile(ProfileId::fromString('2')))
            ->then(
                new ProfileVisited(ProfileId::fromString('2')),
                static fn (Profile $profile) => self::assertSame('1', $profile->id()->toString()),
            );
    }
}

Note

When then() receives only closures and no event objects, it strictly asserts that zero events were emitted.

Using Commandbus like syntax

When using the command bus and the #[Handle] attributes in your aggregate you can also provide the command directly for the when method.

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->when(new CreateProfile(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de')))
            ->then(new ProfileCreated(ProfileId::fromString('1'), Email::fromString('hq@patchlevel.de')));
    }
}

If more parameters than the command is needed, these can also be provided as additional parameters for when. In this example the we need a string which will be directly passed to the event.

final class ProfileTest extends AggregateRootTestCase
{
    // protected function aggregateClass(): string;

    public function testBehaviour(): void
    {
        $this
            ->given(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
            )
            ->when(new VisitProfile(ProfileId::fromString('2')), 'Extra Parameter / Dependency')
            ->then(new ProfileVisited(ProfileId::fromString('2'), 'Extra Parameter / Dependency'));
    }
}

Testing Subscriber

For testing a subscriber there is a utility class which you can use. Using SubscriberUtilities will provide you a bunch of dx features which makes the testing easier. First, you will need to provide the utility class the subscriptions you will want to test, this is done when initializing the class. After that, you can call these 3 methods: executeSetup, executeRun and executeTeardown. These methods will be calling the right methods which are defined via the attributes. For our example we are taking as simplified subscriber:

use Patchlevel\EventSourcing\Attribute\Setup;
use Patchlevel\EventSourcing\Attribute\Subscribe;
use Patchlevel\EventSourcing\Attribute\Subscriber;
use Patchlevel\EventSourcing\Attribute\Teardown;

#[Subscriber('profile_subscriber', RunMode::FromBeginning)]
final class ProfileSubscriber
{
    public int $called = 0;

    #[Subscribe(ProfileCreated::class)]
    public function run(): void
    {
        $this->called++;
    }

    #[Setup]
    public function setup(): void
    {
        $this->called++;
    }

    #[Teardown]
    public function teardown(): void
    {
        $this->called++;
    }
}

With this, we can now write our test for it:

use Patchlevel\EventSourcing\Attribute\Subscriber;
use Patchlevel\EventSourcing\Subscription\RunMode;
use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities;

final class ProfileSubscriberTest extends TestCase
{
    use SubscriberUtilities;

    public function testProfileCreated(): void
    {
        $subscriber = new ProfileSubscriber(/* inject deps, if needed */);

        $util = new SubscriberUtilities($subscriber);
        $util->executeSetup();
        $util->executeRun(
            new ProfileCreated(
                ProfileId::fromString('1'),
                Email::fromString('hq@patchlevel.de'),
            )
        );
       $util->executeTeardown();

        self::assertSame(3, $subscriber->count);
    }
}

This Util class can be used for integration or unit tests.

You can also pass Message instances with additional headers to the executeRun method. This allows testing subscribers that rely on additional parameters like header information:

use Patchlevel\EventSourcing\Attribute\Subscribe;
use Patchlevel\EventSourcing\Attribute\Subscriber;
use DateTimeImmutable;

#[Subscriber('profile_subscriber', RunMode::FromBeginning)]
final class ProfileSubscriber
{
    #[Subscribe(ProfileCreated::class)]
    public function run(ProfileCreated $event, DateTimeImmutable $recordedOn): void
    {
    }
}

Add any headers you want in the test:

use Patchlevel\EventSourcing\Attribute\Subscriber;
use Patchlevel\EventSourcing\Message\Message;
use Patchlevel\EventSourcing\Store\Header\RecordedOnHeader;
use Patchlevel\EventSourcing\Subscription\RunMode;
use Patchlevel\EventSourcing\PhpUnit\Test\SubscriberUtilities;
use DateTimeImmutable;

final class ProfileSubscriberTest extends TestCase
{
    use SubscriberUtilities;

    public function testProfileCreated(): void
    {
        /* Setup and Teardown as before */

        $util->executeRun(
            Message::createWithHeaders(
                new ProfileCreated(
                    ProfileId::fromString('1'),
                    Email::fromString('hq@patchlevel.de'),
                ),
                [new RecordedOnHeader(new DateTimeImmutable('now'))],
            )
        );

       /* Your assertions */
    }
}

patchlevel/event-sourcing-phpunit 适用场景与选型建议

patchlevel/event-sourcing-phpunit 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 103.34k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 01 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「testing」 「phpunit」 「ddd」 「event-sourcing」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 patchlevel/event-sourcing-phpunit 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 patchlevel/event-sourcing-phpunit 我们能提供哪些服务?
定制开发 / 二次开发

基于 patchlevel/event-sourcing-phpunit 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 103.34k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 17
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-23