当我在调试单元测试期间没有断点时,我无法弄清楚为什么会引发异常。但是,当我在下一行设置断点进行调试时,它运行正常。
这是我的代码。
MainPageViewModel.cs
public class MainPageViewModel
{
public async Task<IEnumerable<Event>> GetAllEvents()
{
WebClient client = new WebClient();
string xmlDoc = await FXNewsAlert.Misc.Extensions.DownloadStringTask(client, new Uri("http://www.forexfactory.com/ffcal_week_this.xml")); //breakpoint here
var events = XDocument.Parse(xmlDoc)
.Descendants("event")
.Select(n => new Event
{
Title = n.Element("title").Value,
Country = n.Element("country").Value,
DateTime = this.ToLocalTime(String.Format("{0} {1}", n.Element("date").Value, n.Element("time").Value)),
Impact = n.Element("forecast").Value,
Forecast = n.Element("forecast").Value,
Previous = n.Element("previous").Value
}).ToList();
return events;
}
}
事件测试.cs
[TestClass]
public class EventsTest : WorkItemTest
{
[TestMethod]
[Asynchronous]
public async void GetAllEventsTest()
{
MainPageViewModel vm = new MainPageViewModel();
IEnumerable<Event> events = await vm.GetAllEvents(); //WebException is thrown here.
Assert.IsTrue(events.Count() > 0);
EnqueueTestComplete();
}
}
我的猜测是不知何故加载url需要时间,所以通过断点它可以提供额外的时间,以便我下载的xml可以按时完成。
但它实际上是一个异步方法,所以没关系吧?我现在几乎迷路了。任何帮助将不胜感激。
编辑:DownloadStringTask 的实现
public static Task<string> DownloadStringTask(this WebClient webClient, Uri uri)
{
var tcs = new TaskCompletionSource<string>();
webClient.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
tcs.SetException(e.Error);
}
else
{
tcs.SetResult(e.Result);
}
};
webClient.DownloadStringAsync(uri);
return tcs.Task;
}
System.Net.WebException 的 StackTrace
在 System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) 在 System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 在 System.Net.WebClient.GetWebResponse(WebRequest 请求,IAsyncResult 结果) 在 System.Net .WebClient.DownloadBitsResponseCallback(IAsyncResult result) --- 从先前引发异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()
at FXNewsAlert.Resources.MainPageViewModel.<GetAllEvents>d__2.MoveNext()
--- 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
1.GetResult() 在 FXNewsAlertTest.UnitTests.EventsTest.d__0.MoveNext()