0

我正在尝试为 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)));

为了避免Returns(Task.FromResult(default(Task)))每次模拟异步方法(返回任务)时都必须输入,我虽然会尝试编写一个名为 ReturnsTask 的扩展方法:

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

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

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]]'.

编辑

完整的堆栈跟踪

System.InvalidCastException:无法转换类型为“Telerik.JustMock.Expectations.FuncExpectation 1[System.Threading.Tasks.Task]' to type 'Telerik.JustMock.Expectations.FuncExpectation1[System.Threading.Tasks.Task`1[System.Threading.Tasks.Task]]”的对象。

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)

115 号线

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

57 号线

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

        **man.Arrange(manager => manager.SendPending(Arg.IsAny<TaskList>()))**
            .DoInstead(() => counter++ )
            .ReturnsTask()
            .MustBeCalled();
4

0 回答 0