Home > OS >  How to unit test method with IAsyncEnumerable<dynamic> return type
How to unit test method with IAsyncEnumerable<dynamic> return type

Time:12-16

I have a method:

public async IAsyncEnumerable<dynamic> Query(string name)
{
   if (string.IsNullOrWhiteSpace(name))
      throw new ArgumentException("Name is missing", nameof(name));

   await foreach(var item in _myService.CallSomethingReturningAsyncStream(name))
   {
       yield return item;
   }
}

How to write an unit test for this method, using Nunit?

This is my current approach:

[Test]
[TestCase("")]
[TestCase(null)]
[TestCase("     ")]
public void TestQuery_GivenInvalidName_ShouldThrowException(string invalidName)
{     
    Assert.ThrowsAsync<ArgumentException>(
       async () => 
       await Task.FromResult(_queryService.Query(invalidName)
    );
}

I have tried using Assert.Throws and Assert.ThrowsAsync, but there is no result returned.

CodePudding user response:

This code actually enumerates the IAsyncEnumerable and checks if there is a ArgumentException occurring (at any stage of the enumeration):

Assert.ThrowsAsync<ArgumentException>(
   async () => { await foreach (var x in _queryService.Query(invalidName)) { } });

Using System.Linq.Async this can be shortened to

Assert.ThrowsAsync<ArgumentException>(
   async () => await _queryService.Query(invalidName).ToListAsync());
  • Related