簡體   English   中英

適用於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
}

還要注意,測試已更新為返回async Task而不是async void

參考起訂量快速入門

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM