jeudi 28 janvier 2016

How to unit test a method that uses Task.WhenAll

Let's say we have the following class:

class SampleClass
{
    private readonly IList<int> _numberList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public void MethodToBeTested()
    {
        Task.WhenAll(_numberList.Select(async number => { await Task.Run(() => { ProcessNumber(number); }); }));
    }

    private static void ProcessNumber(int number)
    {
        Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId} Number:{number}");
        Thread.Sleep(1000);
    }
}

and we add the following unit test:

[Test]
public void TestMethodToBeTested()
{
    var sampleClass = new SampleClass();
    _sampleClass.MethodToBeTested();
}

The problem is that when the test runs, it doesn't wait for the MethodToBeTested to finish the execution so the output varies. Is there any way to test the full run of this method using NUnit, without changing the method signature (from void to Task) ?

Aucun commentaire:

Enregistrer un commentaire