模拟任务延迟 [英] Mocking Task.Delay

查看:106
本文介绍了模拟任务延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一行的方法:await Task.Delay(waitTime).ConfigureAwait(false);

I have a method with the following line: await Task.Delay(waitTime).ConfigureAwait(false);

我有一个很好的策略,可以避免在单元测试时实际等待几秒钟,而是验证我们尝试等待特定的秒数.

I there a good strategy to avoid actually waiting the few seconds when unit testing and instead verify that we tried to wait a specific number of seconds.

例如,有一种方法可以向我的方法中注入一个额外的参数,就像在这个(人为的)示例中一样,其中我注入了一个虚构的ITaskWaiter接口的模拟对象:

For instance, is there a way to inject an additional parameter into my method like in this (contrived) example where I inject a mocked object of a fictitious ITaskWaiter interface:

// Arrange
var mockWait = new Mock<ITaskWaiter>(MockBehavior.Strict);
mockWait.Setup(w => w.Delay(It.Is<TimeSpan>(t => t.TotalSeconds == 2)));

// Act
myObject.MyMethod(mockWait.Object);

// Assert
mockWait.Verify();

推荐答案

您可以定义一个"delayer"接口,如下所示:

You can define a "delayer" interface like this:

public interface IAsyncDelayer
{
    Task Delay(TimeSpan timeSpan);
}

然后您可以为生产代码提供以下实现:

And then you can provide the following implementation for production code:

public class AsyncDelayer : IAsyncDelayer
{
    public Task Delay(TimeSpan timeSpan)
    {
        return Task.Delay(timeSpan);
    }
}

现在,您的课程看起来像这样:

Now, your class would look something like this:

public class ClassUnderTest
{
    private readonly IAsyncDelayer asyncDelayer;

    public ClassUnderTest(IAsyncDelayer asyncDelayer)
    {
        this.asyncDelayer = asyncDelayer;
    }

    public async Task<int> MethodUnderTest()
    {
        await asyncDelayer.Delay(TimeSpan.FromSeconds(2));

        return 5;
    }
}

这是依赖注入的基本应用.基本上,我们提取了异步等待另一个类的逻辑,并为其创建了一个接口以启用多态.

This is basic application of Dependency Injection. Basically, we extracted the logic of asynchronously waiting to a different class and created an interface for it to enable polymorphism.

在生产中,您将像这样构成对象:

In production, you would compose your object like this:

var myClass = new ClassUnderTest(new AsyncDelayer());

现在,在测试中,您可以创建一个伪造的延迟器,该延迟器将立即返回,如下所示:

Now, in your test you can create a fake delayer that returns immediately like this:

[TestMethod]
public async Task TestMethod1()
{
    var mockWait = new Mock<IAsyncDelayer>();

    mockWait.Setup(m => m.Delay(It.IsAny<TimeSpan>())).Returns(Task.FromResult(0));

    var sut = new ClassUnderTest(mockWait.Object);

    var result = await sut.MethodUnderTest();

    Assert.AreEqual(5, result);
}

这篇关于模拟任务延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆