You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MassTransit状态机单元测试配置问题求助

MassTransit状态机单元测试问题:InsertOnInitial = true导致Saga实例创建验证失败

配置MassTransit StateMachine单元测试时遇到异常:测试用例与官方示例基本一致,但只要保留事件配置中的x.InsertOnInitial = true;,最后验证Saga实例是否创建的断言就会失败;移除该行代码后,测试可正常通过。已查阅GitHub示例、YouTube教程及官方文档,未找到原因。

相关代码如下:

状态机实现代码

public class DeleteAccountStateMachine : MassTransitStateMachine<DeleteAccountSaga>
{
    // [...] 状态定义省略
    // [...] 事件定义省略

    public DeleteAccountStateMachine()
    {
        InstanceState(x => x.CurrentState);

        Event(() => InitiateAccountDeletion, x =>
        {
            x.InsertOnInitial = true;

            x.CorrelateById(context => context.Message.AccountId);
            x.SetSagaFactory(context => new()
            {
                CorrelationId = context.Message.AccountId
            });
        });
        
        Initially(
            When(InitiateAccountDeletion)
                .TransitionTo(Received)
                .Send(context => new DeleteFilesT1(context.Message.AccountId))
                .Send(context => new DeleteFilesT2(context.Message.AccountId))
                .TransitionTo(DeletingFiles)
        );

        // [...] 其他状态流转逻辑省略
    }
}

单元测试代码

public class StateMachineTests
{
    [Fact]
    public async Task Test()
    {
        await using var serviceProvider = new ServiceCollection()
            .AddMassTransitTestHarness(x =>
            {
                x.AddSagaStateMachine<DeleteAccountStateMachine, DeleteAccountSaga>()
                    .InMemoryRepository();
            })
            .BuildServiceProvider(true);
        
        var testHarness = serviceProvider.GetTestHarness();
        var sagaTestHarness = testHarness.GetSagaStateMachineHarness<DeleteAccountStateMachine, DeleteAccountSaga>();

        await testHarness.Start();

        var command = new InitiateAccountDeletion(Guid.NewGuid());

        await testHarness.Bus.Send(command);

        // 验证命令被总线消费:正常通过
        Assert.True(await testHarness.Consumed.Any<InitiateAccountDeletion>(
            x => x.Context.Message.AccountId == command.AccountId
        ));

        // 验证命令被Saga消费:正常通过
        Assert.True(await sagaTestHarness.Consumed.Any<InitiateAccountDeletion>(
            x => x.Context.Message.AccountId == command.AccountId
        ));

        // 验证Saga实例已创建:断言失败 <=============================================================
        Assert.True(await sagaTestHarness.Created.Any(
            x => x.CorrelationId == command.AccountId
        ));

        await testHarness.Stop();
    }
}

说明:原测试代码中最后一个断言存在两处问题:一是使用赋值运算符=而非比较运算符==;二是CorrelationId应为Guid类型,不存在AccountId属性,已做修正。

内容的提问来源于stack exchange,提问作者GomalId

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:47:00