New to Telerik JustMock? Download free 30-day trial

Throws Async

ThrowsAsync method covers a specific case when needed to test negative scenarios in asynchronous calls.

Let us have the system under test:

public class Foo 
{ 
    public async Task AsyncExecute() 
    { 
        await Task.Delay(1000); 
    } 
} 

Assume that during asynchronous execution of AsyncExecute an unhandled exception was thrown and the task has failed. Later, upon task completion, the client code consumes the result and handles the failure. This particular scenarios can be easily simulated by using ThrowsAsync.

Return a failed Task result

The asynchronous method execution can be mocked to fail with specific exception, the result task properties will have the following values:

  • Exception - set to the exception specified in ThrowsAsync.
  • IsCompleted - set to True
  • IsFaulted - set to True

An example on how to use ThrowsAsync to return a failed Task would look in the following way:

[TestMethod] 
public void ShouldReturnFailedTaskOnAsyncMethodCall() 
{ 
    // Arrange 
    var foo = Mock.Create<Foo>(); 
    Mock.Arrange(() => foo.AsyncExecute()).ThrowsAsync<ArgumentException>(); 
 
    // Act 
    var result = foo.AsyncExecute(); 
 
    // Assert 
    Assert.IsTrue(result.IsFaulted); 
    Assert.IsTrue(result.IsCompleted); 
    Assert.IsTrue(result.Exception.InnerException is ArgumentException); 
} 

Like Throws method, ThrowsAsync gives an option to pass arguments to the exception constructor.

In this article