0

I have an async method lik this:

public async IAsyncEnumerable<IEnumerable<Foo>> Load()
    {
       //some times throws exception in this line
        var responseEnumerable =  _crawler.Crawl();
        await foreach (var response in responseEnumerable)
        {
            yield return SomWorks(responseObject);
        }
    }

Now I want to test this method throws exception. How can I do this using xUnit or FluentAssertion and xUnit?

Hamidreza Samadi
  • 637
  • 1
  • 7
  • 24
  • 1
    As a side note, a return type of `IAsyncEnumerable>` is quite atypical. You have a deferred sequence that contains (potentially) deferred sequences. As a user of such an API, I would be puzzled about what behavior to expect. An `IAsyncEnumerable>` or `IAsyncEnumerable` is more common and predictable. – Theodor Zoulias Aug 16 '22 at 05:31
  • @TheodorZoulias thankyou. I Will change the nested `IEnumerable`. but here it is not important. So How can I test method with return type `IAsyncEnumerable` to throws exception – Hamidreza Samadi Aug 16 '22 at 05:41
  • 1
    You can call `await Load().GetAsyncEnumerator().MoveNextAsync()` which should throw the exception. (+using etc) – Jeremy Lakeman Aug 16 '22 at 06:44

1 Answers1

0

Finally I solved my problem in a bad way. but it works. I used try catch.

[Fact]
    public async Task Load_InvalidFilter_ThrowException()
    {
        try
        {
            await service.Load().ToListAsync();
        }
        catch (Exception e)
        {
            e.Should()
                .BeOfType<ValidationException>();

            e.Message
                .Should()
                .Contain("excepted message");
        }

and for not throws exception:

[Fact]
    public async Task Load_ValidFilter_NotThrowException()
    {
        try
        {
            await service.Load(filter).ToListAsync();
            Assert.True(true);
        }
        catch (Exception)
        {
            Assert.True(false);
        }
Hamidreza Samadi
  • 637
  • 1
  • 7
  • 24