首页 > 解决方案 > 在 xunit 测试中触发 MassTransit 消费者时遇到问题

问题描述

我在尝试对一些使用 MassTransit 传奇状态机和消费者的代码进行单元测试时遇到了 2 个问题。我使用 Autofac 作为容器,使用 xUnit 作为测试框架。

我在这里有一个示例单元测试说明这两个问题。

  1. 当只使用 Autofac 容器来设置我的 SagaStateMachine 和 Consumer 时,我不能断言我的状态机或消费者已经消费了任何消息 - 好像它们没有连接到测试总线。
    (测试ExampleTest_AutofacOnly

    我可以通过在测试中引入 a并从而不是ServiceCollection解决线束来解决这个问题,但这感觉像是双重处理。 (测试)ServiceProviderIContainer
    ExampleTest_AutofacAndServiceProvider

  2. 我无法使用InMemoryTestHarness.Bus.Publish()(但我可以触发状态机)触发我的消费者。真正让人恼火的是,我可以使用 触发我的状态机InMemoryTestHarness.Bus.Publish(),然后状态机在处理事件时可以触发消费者。
    (测试ExampleTest2_AutofacOnly& ExampleTest2_AutofacAndServiceProvider

编辑

(2) 在我注释掉一些行之后,似乎不再是问题了。我的示例中的等效行是:

// In my actual unit test the code below causes the test to fail
var state = sagaHarness.Sagas.Select(s => s.CorrelationId == correlationId).Single();
Assert.Equal("Progress state machine", state.Saga.Message);

// 4. Trigger the second consumer
await testHarness.Bus.Publish(new ExampleMessage2
{
    CorrelationId = correlationId,
    Message = "Trigger consumer",
});

// 5. Check that ExampleMessage has been published and received
Assert.True(await testHarness.Published.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));
Assert.True(await testHarness.Consumed.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));
Assert.True(await consumer2Harness.Consumed.Any<ExampleMessage2>(m => m.Context.CorrelationId == correlationId));

当我得到 saga 实例时,sagaHarness.Sagas.Select()它会阻止在它下面发布的消息被使用。

标签: autofacxunitmasstransit

解决方案


推荐阅读