Mittwoch, 10. Juni 2015

"To throw or not to throw": Asserting exceptions on tasks with async/await

For testing exceptional behaviour i like using FluentAssertions Invoking extensions. However, i noticed that using this with async/await seems not to be supported and requires unelegant rewriting (Please, prove me wrong on this). However, using C# 6 await in try-catch this is now very simple to do:



[TestFixture]
class ThrowTest
{
  [Test]
  public async void Task_should_throw()
  {
    await TestTask().ShouldThrow();
  }

  private static async Task TestTask()
  {
    throw new NotImplementedException();
  }
}

static class AsyncTaskAssertExtensions
{
  public static async Task ShouldThrow(this Task task, 
    string because = null) 
    where TException : Exception
  {
    try
    {
      await task;
      Assert.Fail(because ?? $"The specified task was expected to throw '{typeof(TException).Name}', but no exception occured.");
    }
    catch (TException) { }
  }
}

Keine Kommentare:

Kommentar veröffentlichen