【问题标题】:How to seed initial state to a saga in MassTransit test harness?如何在 MassTransit 测试工具中为 saga 播种初始状态?
【发布时间】:2021-08-05 16:13:17
【问题描述】:

在以前版本的 MassTransit 中,在编写单元测试时,我曾经通过调用 InMemorySagaRepository.Add() 方法来播种 saga 的初始状态:

private InMemorySagaRepository<TState> Repository { get; }

protected async Task SeedSaga<TState>(TState seedState)
    where TState : class, SagaStateMachineInstance
{
    await Repository.Add(new SagaInstance<TState>(seedState), default);
}

此方法将在存储库中以所需状态为 saga 添加一个条目,这可以用作我的测试的起点。

现在我升级到了MassTransit的7.2.1版本,这个方法已经不可用了。

是否可以在InMemorySagaRepository 的当前版本中播种数据?如果没有,可以采取什么方法来获得类似的结果?

谢谢。

【问题讨论】:

    标签: c# .net unit-testing masstransit


    【解决方案1】:

    去年年底有was a discussion on this。总之,您需要使用基于容器的内存中测试工具。

    var services = new ServiceCollection();
    services.AddMassTransitInMemoryTestHarness(x => 
    {
        x.AddSagaStateMachineTestHarness<MySagaStateMachine, MySagaState>();
        x.AddSagaStateMachine<MySagaStateMachine, MySagaState>()
            .InMemoryRepository();
    });
    var provider = services.BuildServiceProvider();
    

    获取并启动测试工具(一定要在finally中停止):

    var harness = provider.GetRequiredService<InMemoryTestHarness>();
    await harness.Start();
    

    您可以获取 saga 字典并添加您的种子 saga 实例:

    var dictionary = provider.GetRequiredService<IndexedSagaDictionary<MySagaState>>();
    dictionary.Add(new SagaInstance(new MySagaState 
    { 
        CorrelationId = ...,
        OtherProperty = ...
    }));
    

    链接的讨论也有一些有用的扩展方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多