繁体   English   中英

在具有 CQRS 模式的 Moq 中使用通用接口

[英]Use generic interface in Moq with CQRS pattern

我有接口 ICommand -> 标记接口

public interface ICommand
{
}

另一个接口 ICommandHandle

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

接下来是 ICommandDispatcher

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

和 CommandDispatcher 类

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

我正在编写单元测试,它将检查用户是否存在。 我想调用我的处理程序并完成整个过程,如创建用户、有效输入参数等。当然,在这种情况下,在内存中我不会连接到我的真实数据库。 我的问题是这段代码是正确的

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

我想知道我应该在测试中使用

new Mock<ICommandHandler>

或者

new Mock<ICommandDispatcher>

但是现在就像您写的那样,我只是想知道我将单元测试与集成测试混淆了?

我觉得这个教程很好: https : //youtu.be/ub3P8c87cwk

单元测试也可能意味着“测试一个特定的类”。 因此,您可以测试 CreateUserHandler 是否正确调用了 HandleAsync()。 但是你不能实际测试用户是否被创建,因为它是需要调用多个“单元”的动作。 为此,通常使用集成测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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