异步方法的C#通用扩展

时间:2013-05-26 18:00:14

标签: c# generics asynchronous telerik extension-methods

我正在尝试为Telerik的JustMock框架创建一个通用的扩展方法。

框架提供了具有以下签名的方法: IAssertable IFunc<T>.Returns(T value)

这样我可以做到以下几点:

var obj = Mock.Create<MyClass>();
obj.Arrange(o => o.GetTitle()).Returns("My Title");

为了模拟异步方法,我会这样做:

 var man = Mock.Create<SyncManager>();

 man.Arrange(manager => manager.SendPending(Arg.IsAny<TaskList>()))
       .Returns(Task.FromResult(default(Task)));

为了避免每次我模拟异步方法(返回Task)时都要输入{​​{1}},我会尝试编写一个名为ReturnsTask的扩展方法:

Returns(Task.FromResult(default(Task)))

但是,当我运行此方法时,我收到以下消息:

public static class MyExtensions
{
    public static IAssertable ReturnsTask<T>(this IFunc<T> func)
    {
        return func.Returns(Task.FromResult(default(T)));
    }
}

修改

完整堆栈跟踪

System.InvalidCastException:无法转换类型为'Telerik.JustMock.Expectations.FuncExpectation System.InvalidCastException : Unable to cast object of type 'Telerik.JustMock.Expectations.FuncExpectation`1[System.Threading.Tasks.Task]' to type 'Telerik.JustMock.Expectations.FuncExpectation`1[System.Threading.Tasks.Task`1[System.Threading.Tasks.Task]]'. 的对象1 [System.Threading.Tasks.Task`1 [System.Threading.Tasks.Task]]'。< / p>

1[System.Threading.Tasks.Task]' to type 'Telerik.JustMock.Expectations.FuncExpectation

第115行

at Telerik.JustMock.Helpers.MultipleReturnValueChainHelper.[](IAssertable )

at Telerik.JustMock.Helpers.MultipleReturnValueChainHelper.Returns(IAssertable assertable, TReturn value)

at Test.MyExtensions.ReturnsTask(IFunc`1 func) in SyncManagerTest.cs: line 115

at Test.SyncManagerTest.<TestSync>d__3.MoveNext() in SyncManagerTest.cs: line 57

--- End of stack trace from previous location where exception was thrown ---

at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)

at NUnit.Core.AsyncSynchronizationContext.AsyncOperation.Invoke()

at NUnit.Core.AsyncSynchronizationContext.AsyncOperationQueue.InvokePendingOperations()

at NUnit.Core.AsyncSynchronizationContext.AsyncOperationQueue.InvokeAll()

at NUnit.Core.AsyncSynchronizationContext.WaitForPendingOperationsToComplete()

at NUnit.Core.NUnitAsyncTestMethod.RunVoidAsyncMethod(TestResult testResult)

第57行

public static class MyExtensions
{
    public static IAssertable ReturnsTask<T>(this IFunc<T> func)
    {
        **return func.Returns(Task.FromResult(default(T)));**
    }
}

0 个答案:

没有答案