您如何模拟IAsyncEnumerable? [英] How do you mock an IAsyncEnumerable?
问题描述
我想对一个方法进行单元测试,该方法调用返回IAsyncEnumerable<T>
的服务的另一个方法.
我已经创建了服务Mock<MyService>
的模拟,我想设置该模拟,但是我不知道该怎么做.是否有可能 ?是否有其他方法可以对调用IAsyncEnumerable
I want to unit test a method that calls another method of a service returning an IAsyncEnumerable<T>
.
I have created a a mock of my service Mock<MyService>
and I want to setUp this mock but I don't know how to do that. Is it possible ? Are there other ways of unit testing a method that calls something retuning an IAsyncEnumerable
public async Task<List<String>> MyMethodIWantToTest()
{
var results = new List<string>();
await foreach(var item in _myService.CallSomethingReturningAsyncStream())
{
results.Add(item);
}
return results;
}
推荐答案
如果您不想做任何特别的事情,例如延迟返回通常是异步枚举的要点,那么您只需创建一个生成器函数即可为您返回值.
If you don’t want to do anything special, e.g. a delayed return which is usually the point of async enumerables, then you can just create a generator function that returns the values for you.
public static async IAsyncEnumerable<string> GetTestValues()
{
yield return "foo";
yield return "bar";
await Task.CompletedTask; // to make the compiler warning go away
}
有了它,您可以简单地为您的服务创建一个模拟并测试您的对象:
With that, you can simply create a mock for your service and test your object:
var serviceMock = new Mock<IMyService>();
serviceMock.Setup(s => s.CallSomethingReturningAsyncStream()).Returns(GetTestValues);
var thing = new Thing(serviceMock.Object);
var result = await thing.MyMethodIWantToTest();
Assert.Equal("foo", result[0]);
Assert.Equal("bar", result[1]);
当然,由于您现在正在使用生成器函数,因此您还可以使其更加复杂并添加实际延迟,甚至包括一些控制收益率的机制.
Of course, since you are now using a generator function, you can also make this more complicated and add actual delays, or even include some mechanism to control the yielding.
这篇关于您如何模拟IAsyncEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!