J2ghz
J2ghz

Reputation: 659

xUnit Assert.All() async

I have this example test using xUnit:

    [Fact]
    public void SomeTest()
    {
        Assert.All(itemList, async item=>
                {
                    var i = await Something(item);
                    Assert.Equal(item,i);
                });
    }

Is there a good solution to make the whole test async/awaitable?

Upvotes: 23

Views: 29924

Answers (2)

Eli Arbel
Eli Arbel

Reputation: 22739

In xUnit 2.4.2 and above, use Assert.AllAsync. Otherwise, you can use Task.WhenAll:

[Fact]
public async Task SomeTest()
{
    var itemList = ...;
    var results = await Task.WhenAll(itemList.Select(async item =>
    {
        var i = await Something(item);
        return i;
    }));
    Assert.All(results, result => Assert.Equal(1, result));
}

Upvotes: 33

Mr Patience
Mr Patience

Reputation: 2180

As for 2023, accepted answer is no longer true, xunit team added Assert.AllAsync: https://github.com/xunit/xunit/discussions/2498

Upvotes: 3

Related Questions