我无法弄清楚为什么在我的单元测试调试期间没有断点时抛出异常。但是,当我使用在以下行设置的断点进行调试时,它运行正常。
这是我的代码。
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;
}
}
EventsTest.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();
}
}
我的猜测是,以某种方式加载网址需要时间,因此通过设置断点,它会给予额外的时间,以便我可以按时完成下载的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结果)
---从抛出异常的先前位置开始的堆栈跟踪结束---
在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在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()
答案 0 :(得分:1)
我觉得FXNewsAlert出了问题,上面没有介绍它的实现。我建议深入研究(或替换)FXNewsAlert.Misc.Extensions.DownloadStringTask()
。我的猜测是它在完成下载之前就已经屈服了。
为了测试这段代码,我首先创建了一个Event类来包含数据,并尽量减少对代码的更改:
public class Event
{
public string Title { get; set; }
public string Country { get; set; }
public DateTime DateTime { get; set; }
public string Impact { get; set; }
public string Forecast { get; set; }
public string Previous { get; set; }
}
然后我稍微修改了你的代码以使用WebClient的DownloadStringTaskAsync()
方法:
public class MainPageViewModel
{
public async Task<IEnumerable<Event>> GetAllEvents()
{
WebClient client = new WebClient();
// HACK: Don't have access to the implementation to FXNewsAlert...
//string xmlDoc = await FXNewsAlert.Misc.Extensions.DownloadStringTask(
// client, new Uri("http://www.forexfactory.com/ffcal_week_this.xml")); //breakpoint here
string xmlDoc = await client.DownloadStringTaskAsync(
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 = DateTime.Parse(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;
}
}
我没有创建测试项目,而是掀起了以下控制台应用程序:
class Program
{
static void Main(string[] args)
{
var vm = new MainPageViewModel();
var task = vm.GetAllEvents();
task.Wait();
foreach (Event e in task.Result)
{
Console.WriteLine("{0} [{1}]", e.Title, e.DateTime);
Console.WriteLine("Forecast: {0} (Previous: {1})", e.Forecast, e.Previous);
Console.WriteLine();
}
}
}
此代码在有和没有断点的情况下都可以正常执行。
答案 1 :(得分:0)
将您的测试方法从async void
更改为async Task
。
这不会清除WebException
,但它应该保持一致,以便您可以调试它。