我在为 StateMachine 配置一些单元测试时遇到问题。
我已经浏览了 GitHub 和 Youtube 中的大部分示例,但我不明白为什么这不起作用。
测试用例本身如下。和官方文档里的差不多。
我注意到的一件事是,如果我删除这件 "x.InsertOnInitial = true;" 测试成功...
public class DeleteAccountStateMachine : MassTransitStateMachine<DeleteAccountSaga>
{
// [...] States...
// [...] Events...
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)
);
// [...]
}
}
// The test class
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);
// Verify that command is consumed by the bus.
// This is OK.
Assert.True(await testHarness.Consumed.Any<InitiateAccountDeletion>(
x => x.Context.Message.AccountId = command.AccountId
));
// Verify that command is consumed by the saga.
// This is OK.
Assert.True(await sagaTestHarness.Consumed.Any<InitiateAccountDeletion>(
x => x.Context.Message.AccountId = command.AccountId
));
// Verify that the saga instance is created.
// This FAILS. <=============================================================
Assert.True(await sagaTestHarness.Created.Any(
x => x.CorrelationId.AccountId = command.AccountId
));
await testHarness.Stop();
}
}