In my previous post I showed how to use awaitable TestCase or Value sources in NUnit 3.14. NUnit 4 continues the story of adding async support by also allowing TestCaseSource, ValueSource, or TestFixtureSource to return an IAsyncEnumerable.
public class AsyncTestSourcesTests
{
[TestCaseSource(nameof(MyMethodAsync))]
public void Test1Async(MyClass item)
{
}
public static async IAsyncEnumerable<MyClass> MyMethodAsync()
{
using var file = File.OpenRead("Path/To/data.json");
await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<MyClass>(file))
{
yield return item;
}
}
public class MyClass
{
public int Foo { get; set; }
public int Bar { get; set; }
}
}
As with IEnumerable-backed sources, NUnit will lazily enumerate the collection to avoid bringing all the objects into memory at once, instead only generating the test or value sources when needed.
Many async enumerable operations also require async disposal of the underlying resource after enumerating the collection. NUnit will also take care of calling the dispose method to ensure everything is cleaned up properly. In the event that both DisposeAsync and Dispose methods are present then NUnit will only call the asynchronous DisposeAsync method and not the Dispose method.

Leave a Reply