[英]Unit test Moq generic type
I'm trying to test a method which returns an Interface with a generic type but I always get this error:我正在尝试测试一个返回具有泛型类型的接口的方法,但我总是收到此错误:
System.ArgumentException : Invalid callback.
System.ArgumentException : 无效的回调。 Setup on method with 0 parameter(s) cannot invoke callback with different number of parameters (1).
具有 0 个参数的方法上的设置无法使用不同数量的参数 (1) 调用回调。 at Moq.MethodCall.SetReturnsResponse g__ValidateCallback|27_0(Delegate callback)
在 Moq.MethodCall.SetReturnsResponse g__ValidateCallback|27_0(委托回调)
Test method:测试方法:
//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);
ClientService 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 is class under test, so you do not need to Mock it. ClientService 是被测试的类,所以你不需要模拟它。 I would do something like this:
我会做这样的事情:
//Arrange
var clientService = new ClientService();
//Act
var client = clientService.GetRabbitClient<AlertRequest>();
//Assert
Assert.NotNull(client);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.