模拟<T> <T> 使用 Moq 实现的每个类的 IEnumerable



我有以下接口

public interface ICommand<TResult, TModel>
{
Task<TResult> DoWorkAsync(TModel model);
}

由一个或多个这样的命令类实现:

public class MyCommand1 : ICommand<Response, Model>()
{
public async Task<Response> DoWorkAsync(Model model) {
// do something
}
}
public class MyCommand2 : ICommand<Response, Model>()
{
public async Task<Response> DoWorkAsync(Model model) {
// do something else
}
}

Respose和Model类别如下:

public class Response
{
public bool IsSuccessful {get;set;}
}
public class Model
{
public Guid Id {get;set;}
public string Name {get;set;}
}

然后我有一个编排器类,它依赖于IEnumerable<ICommand<Response, Model>>的IEnumerable

public class MyOrchestrator
{
private readonly IEnumerable<ICommand<Response, Model>> _commands;
public MyOrchestrator(IEnumerable<ICommand<Response, Model>> commands)
{
_commands = commands;
}
public async Task ExecuteAsync(Model model)
{
myCommand1_Response = await _commands
.OfType<MyCommand1>()
.First()
.DoWorkAsync(model);
myCommand2_Response = await _commands
.OfType<MyCommand2>()
.First()
.DoWorkAsync(model);
// other operations
}
}

现在,在我的测试中,我试图模拟MyOrchestrator类对每个MyCommand类型的依赖IEnumerable<ICommand<Response, Model>>。我怎样才能做到这一点?

问题是MyCommand2和MyCommand1是具体的类。您需要将它们设置为IMyCommand1和IMyCommand 2,或者将DoWorkAsync设置为虚拟。

我认为你可以简化你的orcestator,这会让嘲笑变得微不足道。

public class MyOrchestrator
{
...
public MyOrchestrator(ICommand<Response, Model> command1, ICommand<Response, Model> command2)
{
this.command1 = command1 ?? throw...;
this.command2 = command2 ?? throw...;
}
public async Task ExecuteAsync(Model model)
{
myCommand1_Response = await command1.DoWorkAsync(model);
myCommand2_Response = await command1.DoWorkAsync(model);
// other operations
}
}

现在嘲笑这没什么特别的。

var mockCommand1 = new Mock<ICommand<Response, Model>>(MockBehaviour.Strict);
...
var tested = new MyOrchestrator(command1: mockCommand1.Object, ...); 

最新更新