How to use MSTest to test a C# async method where it doesn’t complete until I feed it more data?

I’m writing unit tests where the SUT is a queue; the language is C#, and I’m using the MSTest framework. One method in the queue, async Task<int[]> DequeueAsync(int count), waits until the queue contains enough items before returning the requested number of them in an array. I want to verify that if I call DequeueAsync() requesting n+k items but the queue presently only contains n items, the method will wait until I enqueue at least k more items before returning the result. So, for example, I might call DequeAsync(count: 10) when there are only four items in the queue, and then enqueue another six items so that there are now ten items in the queue, allowing DequeueAsync() to return. But if I use await, won’t the task block, preventing me from feeding the additional six items to the queue? How can I start the task and then do the other stuff the task relies upon to complete?

I have successfully tested the method when there are sufficient items in the queue to immediately return the requested number, but I don’t have any idea how to test the scenario where I call the method and then resume execution so I can do additional stuff the method requires before it will return.

4

As I understand it, you’ve designed a queue similar to this class that I made to try and reproduce your issue.

public class QueueThatWaitsForN<T> : Queue<T>
{
    object _criticalSection = new object();
    public async Task<T[]> DequeueAsync(int n, int pollingMs = 100, CancellationToken? token = null)
    {
        while (true)
        {
            if (token is CancellationToken valid)
            {
                if (valid.IsCancellationRequested)
                {
                    // Return empty or partial contents.
                    return localDequeueN();
                }
            }
            else
            {
                int captureCount;
                lock (_criticalSection)
                {
                    captureCount = Count;
                }
                if (captureCount >= n)
                {
                    return localDequeueN();
                }
                await Task.Delay(Math.Max(10, pollingMs));
            }
        }
        T[] localDequeueN()
        {
            var builder = new List<T>();
            lock (_criticalSection)
            {
                while (Count > 0 && builder.Count < n)
                {
                    builder.Add(Dequeue());
                }
                return builder.ToArray();
            }
        }
    }    
    public new void Enqueue(T t)
    {
        lock (_criticalSection)
        {
            base.Enqueue(t);
        }
    }
}


And your question is:

how to test the scenario where I call the method and then resume execution so I can do additional stuff the method requires before it will return.

In other words, you’re trying to await your SUT and then supply it with some data to enqueue, but if you’re blocked awaiting the dequeue then how can you supply the data that would ever make it resume execution from the await?

It may seem counterintuitive, but the Task that is going to populate your SUT needs to be started before any awaits that you perform on it. Here’s how that might look:

[TestMethod("Asynchronous test of Queue N")]
public async Task TestQueueN()
{
    Random
        randoDelay = new Random(),
        randoLength = new Random(Seed:1);
    object randoLock = new object();
    var SUT = new QueueThatWaitsForN<char>();
    int testValue = 0;
    bool isCanceled = false;
    Task? loop = null;
    var output = new StringBuilder();
    output.AppendLine(); // cosmetic to make the limit left-aligned
    try
    {
        loop = Task.Run(async () =>
        {
            while (!isCanceled)
            {
                await Task.Delay(randoDelay.Next(1, 10));
                SUT.Enqueue($"{testValue++}".Last());
            }
        });
    }
    catch (OperationCanceledException)
    { }
    const int NLOOP = 10;
    for (int i = 0; i < NLOOP; i++)
    {
        int limit;
        lock (randoLock)
        {
            limit = randoLength.Next(5, 25);
        }
        var result = await SUT.DequeueAsync(limit);
        var line = $"Requested: {limit} Received: {string.Join(string.Empty, result)}";
        output.AppendLine(line);
        Console.WriteLine(line);
        Assert.AreEqual(
            expected: limit,
            actual: result.Length,
            $"Expecting queue to wait for {limit}");
    }
    isCanceled = true;
    if (loop is not null) await loop.WaitAsync(timeout: TimeSpan.FromSeconds(5));
    Assert.AreEqual(
        expected: @"
Requested: 9 Received: 012345678
Requested: 7 Received: 9012345
Requested: 14 Received: 67890123456789
Requested: 20 Received: 01234567890123456789
Requested: 18 Received: 012345678901234567
Requested: 13 Received: 8901234567890
Requested: 12 Received: 123456789012
Requested: 23 Received: 34567890123456789012345
Requested: 7 Received: 6789012
Requested: 17 Received: 34567890123456789
",
        actual: output.ToString(),
        "Expecting pseudorandom output to match because of (Seed:1)");
    { }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật