Nsubstitute的延迟回报
我有一个接口idiscosclient
,用于测试/演示目的时,我希望在.getSingle< t>()方法的随机延迟在1到5秒之间。这主要是这样,我可以看到我所有的各种负载旋转器组件以及什么都没有起作用。
因此,我认为我能够做这样的事情:
Fixture fixture = new();
fixture.Customize(new DiscosModelFixtureCustomizationNoLinks());
builder.Services.AddTransient(_ =>
{
IDiscosClient client = Substitute.For<IDiscosClient>();
DiscosObject obj = fixture.Create<DiscosObject>();
client.GetSingle<DiscosObject>(Arg.Any<string>()).Returns(Task.Delay(Random.Shared.Next(1000,5000)).ContinueWith(_ => obj));
return client;
});
但是,虽然当我第一次调用该方法时似乎有延迟每次我称其为idiscosclient
实例。
有足够简单的方法来实现这一目标吗?
I have an interface IDiscosClient
, for testing/demo purposes while I'm developing the app, I want a mock to return a new model when the .GetSingle<T>()
method is called with a random delay of between 1 and 5 seconds. This is mostly so I can see that all of my various loading spinner components and whatnot work.
So, I thought I'd be able to do something like this:
Fixture fixture = new();
fixture.Customize(new DiscosModelFixtureCustomizationNoLinks());
builder.Services.AddTransient(_ =>
{
IDiscosClient client = Substitute.For<IDiscosClient>();
DiscosObject obj = fixture.Create<DiscosObject>();
client.GetSingle<DiscosObject>(Arg.Any<string>()).Returns(Task.Delay(Random.Shared.Next(1000,5000)).ContinueWith(_ => obj));
return client;
});
However, while there seems to be a delay when I first call the method, once this has resolved, it just seems to return the completed task with the same model in it every time I call it for that IDiscosClient
instance.
Is there a simple enough way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,问题在于,上面的代码仅创建一个新的
任务
第一次返回了每个后续时间(已经完成的)。为了解决此问题,我们可以将上述代码更改为:
或者,出于遗产,我们可以将其提取到方法中并制作整个代码块:
So the issue is that the code above only creates a fresh
Task
the first time and then returns the same one (which has already completed) each subsequent time.To fix this, we can either change the code above to:
Or, for legibilities sake, we can extract it into a method and make the whole code block: