0
votes

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. 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)

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>>();
    }
}
1
May be Object is a problem? You use .Object in Returns and in Act. Try delete .Object in Returns - Sasha
I get this if I remove the Object in Returns : Cannot implicitly convert type 'Mock<IMessageQueueClient<AlertRequest>>' to 'IMessageQueueClient<TAlertRequest>'. An explicit conversion exists (are you missing a cast?) - Gun
Then move back .Object in returns in try this var client = clientService.GetRabbitClient<AlertRequest>(); - Sasha

1 Answers

1
votes

ClientService is class under test, so you do not need to Mock it. I would do something like this:

//Arrange
var clientService = new ClientService();

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

//Assert
Assert.NotNull(client);