单元测试起订量通用类型

Unit test Moq generic type

我正在尝试测试一个 returns 具有通用类型的接口的方法,但我总是收到此错误:

System.ArgumentException : Invalid callback. Setup on method with 0 parameter(s) cannot invoke callback with different number of parameters (1). at Moq.MethodCall.SetReturnsResponse g__ValidateCallback|27_0(Delegate callback)

测试方法:

//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);

客户端服务class:

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 正在 class 测试中,因此您不需要模拟它。我会做这样的事情:

//Arrange
var clientService = new ClientService();

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

//Assert
Assert.NotNull(client);