【发布时间】:2016-05-23 22:17:41
【问题描述】:
我想创建一个“模拟”IHttpFilter 实现,用于使用Windows.Web.Http HttpClient 测试调用。这是我在实现中的 SendRequestAsync 方法
public IAsyncOperationWithProgress<HttpResponseMessage,HttpProgress>
SendRequestAsync(HttpRequestMessage request)
{
HttpResponseMessage response = new HttpResponseMessage(_statusCode);
response.Content = _content;
//This is the problematic part
return AsyncInfo.Run<HttpResponseMessage, HttpProgress>(
(token, progress) => Task.Run<HttpResponseMessage>(
() => { return response; }));
}
在我的测试方法中,我是这样使用它的。这也是在应用程序中使用HttpClient 的方式。
//This Throws an InvalidCastException
var result = await client.SendRequestAsync(new HttpRequestMessage(HttpMethod.Get, new Uri("http://www.nomatter.com")));
但它会抛出 InvalidCastException
Result Message: Test method UnitTestLibrary1.UnitTest.TestHttp threw exception:
System.InvalidCastException: Specified cast is not valid.
Result StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at UnitTestLibrary1.UnitTest.<TestHttp>d__0.MoveNext() in c:\Users\****\UniversalPCLUnitTest\UnitTestLibrary1\UnitTest1.cs:line 40
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
我无法找出引发异常的原因。有人遇到过同样的问题吗?
【问题讨论】:
标签: c# unit-testing windows-runtime mocking tdd