From 37bb4d38358d9acf97d031e0867388a54124d55a Mon Sep 17 00:00:00 2001 From: stakx Date: Sat, 3 Jun 2017 21:21:18 +0200 Subject: [PATCH] Add `ThrowsAsync` overload for non-generic `Task` --- Source/ReturnsExtensions.cs | 14 ++++++++++++++ UnitTests/ReturnsExtensionsFixture.cs | 15 +++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/Source/ReturnsExtensions.cs b/Source/ReturnsExtensions.cs index 79016d1b8..3ba16ccc6 100644 --- a/Source/ReturnsExtensions.cs +++ b/Source/ReturnsExtensions.cs @@ -35,6 +35,20 @@ public static IReturnsResult ReturnsAsync(this IReturns Task.FromResult(valueFunction())); } + /// + /// Specifies the exception to throw when the asynchronous method is invoked. + /// + /// Mocked type. + /// Returns verb which represents the mocked type and the task return type + /// Exception instance to throw. + public static IReturnsResult ThrowsAsync(this IReturns mock, Exception exception) where TMock : class + { + var tcs = new TaskCompletionSource(); + tcs.SetException(exception); + + return mock.Returns(tcs.Task); + } + /// /// Specifies the exception to throw when the asynchronous method is invoked. /// diff --git a/UnitTests/ReturnsExtensionsFixture.cs b/UnitTests/ReturnsExtensionsFixture.cs index 0ba895fe1..be2c630ee 100644 --- a/UnitTests/ReturnsExtensionsFixture.cs +++ b/UnitTests/ReturnsExtensionsFixture.cs @@ -9,6 +9,8 @@ public class ReturnsExtensionsFixture { public interface IAsyncInterface { + Task NoParametersNonGenericTaskReturnType(); + Task NoParametersRefReturnType(); Task NoParametersValueReturnType(); @@ -192,6 +194,19 @@ public void ReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation() Assert.NotSame(firstEvaluationResult, secondEvaluationResult); } + [Fact] + public void ThrowsAsync_on_NoParametersNonGenericTaskReturnType() + { + var mock = new Mock(); + 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() {