Skip to content

Commit

Permalink
Add ThrowsAsync overload for non-generic Task
Browse files Browse the repository at this point in the history
  • Loading branch information
stakx committed Jun 5, 2017
1 parent f8e6187 commit 37bb4d3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Source/ReturnsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ public static class ReturnsExtensions
return mock.Returns(() => Task.FromResult(valueFunction()));
}

/// <summary>
/// Specifies the exception to throw when the asynchronous method is invoked.
/// </summary>
/// <typeparam name="TMock">Mocked type.</typeparam>
/// <param name="mock">Returns verb which represents the mocked type and the task return type</param>
/// <param name="exception">Exception instance to throw.</param>
public static IReturnsResult<TMock> ThrowsAsync<TMock>(this IReturns<TMock, Task> mock, Exception exception) where TMock : class
{
var tcs = new TaskCompletionSource<bool>();
tcs.SetException(exception);

return mock.Returns(tcs.Task);
}

/// <summary>
/// Specifies the exception to throw when the asynchronous method is invoked.
/// </summary>
Expand Down
15 changes: 15 additions & 0 deletions UnitTests/ReturnsExtensionsFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ public class ReturnsExtensionsFixture
{
public interface IAsyncInterface
{
Task NoParametersNonGenericTaskReturnType();

Task<string> NoParametersRefReturnType();

Task<int> NoParametersValueReturnType();
Expand Down Expand Up @@ -192,6 +194,19 @@ public void ReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation()
Assert.NotSame(firstEvaluationResult, secondEvaluationResult);
}

[Fact]
public void ThrowsAsync_on_NoParametersNonGenericTaskReturnType()
{
var mock = new Mock<IAsyncInterface>();
var exception = new InvalidOperationException();
mock.Setup(x => x.NoParametersNonGenericTaskReturnType()).ThrowsAsync(exception);

var task = mock.Object.NoParametersNonGenericTaskReturnType();

Assert.True(task.IsFaulted);
Assert.Equal(exception, task.Exception.InnerException);
}

[Fact]
public void ThrowsAsync_on_NoParametersRefReturnType()
{
Expand Down

0 comments on commit 37bb4d3

Please sign in to comment.