简体   繁体   中英

Use generic interface in Moq with CQRS pattern

I have interface ICommand -> marker interaface

public interface ICommand
{
}

another interface ICommandHandle

public interface ICommandHandler<T> where T : ICommand
{
    Task HandleAsync(T command);
}

Next is ICommandDispatcher

public interface ICommandDispatcher : ICommand
{
    Task DispatchAsync<T>(T command) where T : ICommand; 
}

and CommandDispatcher class

public class CommandDispatcher : ICommandDispatcher
{
    private readonly IComponentContext _context;

    public CommandDispatcher(IComponentContext componentContext)
    {
        _context = componentContext;
    }

    public async Task DispatchAsync<T>(T command) where T : ICommand
    {
        if (command == null)
            throw new ArgumentNullException(nameof(command), "Command can not be null");

        var handler = _context.Resolve<ICommandHandler<T>>();
        await handler.HandleAsync(command);
    }
}

I'm writing unit test which will be check that user exist or not. I want to invoke my handler and go through the whole process like create user, valid input parameter etc. Of course in memory I won't connect with my real database in this case. And my question is that this code is correct

var commandDispatcher = new Mock<ICommandHandler<CreateUser>>();
var command = new CreateUser
{
    Name = "user",
    Email = "user@email.com"
};

var client = new Client("user", "user@email.com");
commandDispatcher.Setup(x => x.HandleAsync(command));   

I'm wondering should I use in test

new Mock<ICommandHandler>

or

new Mock<ICommandDispatcher>

But now like you wrote I just wondering that I confused unit test with integration test ?

I find this tutorial good: https://youtu.be/ub3P8c87cwk

Also Unit testing can mean something as "Testing one particular class". So you can test that CreateUserHandler is correctly calling HandleAsync(). But you cant actualy test whether user is created, because it is action that requires multiple "units" to be called. For this the integration tests are usually used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM