简体   繁体   English

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

[英]Use generic interface in Moq with CQRS pattern

I have interface ICommand -> marker interaface我有接口 ICommand -> 标记接口

public interface ICommand
{
}

another interface ICommandHandle另一个接口 ICommandHandle

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

Next is ICommandDispatcher接下来是 ICommandDispatcher

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

and CommandDispatcher class和 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);
    }
}

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我觉得这个教程很好: 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().因此,您可以测试 CreateUserHandler 是否正确调用了 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.为此,通常使用集成测试。

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

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