簡體   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