簡體   English   中英

單元測試 Moq 泛型類型

[英]Unit test Moq generic type

我正在嘗試測試一個返回具有泛型類型的接口的方法,但我總是收到此錯誤:

System.ArgumentException : 無效的回調。 具有 0 個參數的方法上的設置無法使用不同數量的參數 (1) 調用回調。 在 Moq.MethodCall.SetReturnsResponse g__ValidateCallback|27_0(委托回調)

測試方法:

//Arrange
Mock<IClientService> clientService = new Mock<IClientService>();

clientService
    .Setup(x => x.GetRabbitClient<AlertRequest>())
    .Returns<IMessageQueueClient<AlertRequest>>(x => new Mock<IMessageQueueClient<AlertRequest>>().Object);

//Act
var client = clientService.Object.GetRabbitClient<AlertRequest>();

//Assert
Assert.NotNull(client);

客戶端服務類:

public class ClientService : IClientService
{
    /// <inheritdoc />
    public IMessageQueueClient<TMessage> GetRabbitClient<TMessage>() where TMessage : class, new()
    {
        ServiceCollection serviceCollection = new ServiceCollection();
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
        serviceCollection.UseMessageQueueOptions<RabbitMQSettings>(configuration);
        serviceCollection.UseMessageQueueFor<TMessage>();
        var serviceProvider = serviceCollection.BuildServiceProvider();

        return serviceProvider.GetRequiredService<IMessageQueueClient<TMessage>>();
    }
}

ClientService 是被測試的類,所以你不需要模擬它。 我會做這樣的事情:

//Arrange
var clientService = new ClientService();

//Act
var client = clientService.GetRabbitClient<AlertRequest>();

//Assert
Assert.NotNull(client);

暫無
暫無

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

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