适用于MassTransit使用者的XUnit单元测试

时间:2019-08-29 23:11:05

标签: c# moq xunit 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);

1 个答案:

答案 0 :(得分:0)

由于您尚未弄清什么实际上不起作用,所以我能提供的最多就是如何创建模拟上下文并将其传递给测试中的主题方法。

这很简单,因为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
}

还要注意,测试已更新为返回async Task而不是async void

引用Moq Quickstart

相关问题