MassTransit 消费者的 XUnit 单元测试

XUnit unit tests for MassTransit consumer

我使用的是 MassTransit 5.5.5 版本和 xunit 2.4.1

我的消费者是这样的

public class StorageInformationConsumer : IConsumer<CreateStorageInformationSummary>
{
    private readonly IBus _serviceBus;
    private readonly USIntegrationQueueServiceContext _USIntegrationQueueServiceContext;


    public StorageInformationConsumer(IBus serviceBus, USIntegrationQueueServiceContext USIntegrationQueueServiceContext)
    {
        _serviceBus = serviceBus;
        _USIntegrationQueueServiceContext = USIntegrationQueueServiceContext;
    }

    public async Task Consume(ConsumeContext<CreateStorageInformationSummary> createStorageInformationSummarycontext)
    {
        //....
    }
}

我的测试是这样的

public class StorageInformationConsumerTest
{
    private readonly USIntegrationQueueServiceContext _dbContext;
    private readonly Mock<IBus> _serviceBusMock;
    private readonly StorageInformationConsumer _storageInformationConsumer;

    public StorageInformationConsumerTest()
    {
        var options = new DbContextOptionsBuilder<USIntegrationQueueServiceContext>()
                    .UseInMemoryDatabase(databaseName: "InMemoryArticleDatabase")
                    .Options;
        _dbContext = new USIntegrationQueueServiceContext(options);
        _serviceBusMock = new Mock<IBus>();
        _storageInformationConsumer = new StorageInformationConsumer(_serviceBusMock.Object, _dbContext);
    }

    [Fact]
    public async void ItShouldCreateStorageInformation()
    {
        var createStorageInformationSummary = new CreateStorageInformationSummary
        {
            ClaimNumber = "C-1234",
            WorkQueueItemId = 1,
            StorageInformation = CreateStorageInformation(),
        };

        //How to consume
    }
}

如何消费 CreateStorageInformationSummary 消息以调用消费者,以下不起作用

var mockMessage = new Mock<ConsumeContext<CreateStorageInformationSummary>>(createStorageInformationSummary);
await _storageInformationConsumer.Consume(mockMessage.Object);

由于您还没有弄清楚到底是什么不起作用,我最多只能提供如何创建模拟上下文并将其传递给被测主题方法。

这很简单,因为 ConsumeContext<T> 已经是一个接口

[Fact]
public async Task ItShouldCreateStorageInformation() {
    //Arrange
    var createStorageInformationSummary = new CreateStorageInformationSummary {
        ClaimNumber = "C-1234",
        WorkQueueItemId = 1,
        StorageInformation = CreateStorageInformation(),
    };
    //Mock the context
    var context = Mock.Of<ConsumeContext<CreateStorageInformationSummary>>(_ => 
        _.Message == createStorageInformationSummary);

    //Act
    await _storageInformationConsumer.Consume(context);

    //Assert
    //...assert the expected behavior
}

另请注意,测试已更新为 return async Task 而不是 async void

引用Moq Quickstart