如何将初始状态播种到 MassTransit 测试工具中的传奇?

How to seed initial state to a saga in MassTransit test harness?

在以前版本的 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);
}

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

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

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

谢谢。

去年年底有 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();

获取并启动测试工具(确保在最后停止它):

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

您可以获得saga字典并添加您的seed saga实例:

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

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