简体   繁体   English

如何对使用等待延迟的方法进行单元测试

[英]How to unit test method that uses await delay

I have created dummy code to describe my issue as follows: 我创建了伪代码来描述我的问题,如下所示:

  public class ItemGenerator
    {
        public bool isStopped;
        public List<int> list = new List<int>();
        public void GetItems(int itemsPerSecond)
        {
            int i = 0;
            while (!isStopped)
            {
                list.add(i);
                await Task.Delay(1000);
                i++;
            }
        }
    }



    [Test]
    public void TestGetItmes()
    {
        ItemGenerator gen = new ItemGenerator();

        gen.GetItems(1000);

        await  Task.Delay(5000).ContinueWith(t =>
        {
            gen.isStopped = true;
            Assert.True(gen.list.Count() == (5 * 1000));
        });
    }

Now the problem is that the assert will fail sporadically, I guess it's to do with CPU performance and the fact that there is no guarantee that delay of 1000 will be always 1000ms but what would be the best approach to UT this kind of logic ? 现在的问题是,断言将偶尔失败,我想这与CPU性能有关,并且不能保证延迟1000始终为1000ms,但这是UT这种逻辑的最佳方法是什么呢?

Here's how I would approach this - firstly use the built in CancellationToken 这是我的处理方式-首先使用内置的CancellationToken

public class ItemGenerator
{
    public List<int> List { get; } = new List<int>();

    public async Task GetItems(CancellationToken token)
    {
        int i = 0;
        while(!token.IsCancellationRequested)
        {
            List.Add(i);
            await Task.Delay(1000);
            i++;
        }
    }
}

Then your test can make use of CancellationTokenSource and specifically CancelAfter method: 然后您的测试可以使用CancellationTokenSource ,特别是使用CancelAfter方法:

var gen = new ItemGenerator();

CancellationTokenSource src = new CancellationTokenSource();
src.CancelAfter(5000);
await gen.GetItems(src.Token);

Note you could pass the CancellationToken in to the constructor of ItemGenerator instead of the method if that is more appropriate. 注意,您可以将CancellationToken传递给ItemGenerator的构造函数,而不是更合适的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM