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
相关产品推荐
相关产品推荐

