在 Windows Phone 7 中对 WebClient 进行单元测试
我的应用程序中有一些 WebClient 请求,并且想要在单元测试中检查检索到的数据的解析。如何在 WP7 Silverlight UnitTestFramework 中等待事件 client_DownloadStringCompleted?
I have some of WebClient Requests in my App and want to check the parsing of the retrieved data in a unit test. How Do I wait in the WP7 Silverlight UnitTestFramework for the event client_DownloadStringCompleted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的方法是围绕
WebClient
引入一个包装类(好吧,我实际上最终使用了HttpWebRequest
,因为WebClient
做了太多的事情在 UI 线程中...) 实现一个接口。然后,我可以创建一个实现IWebClient
的FakeWebClient
,允许我验证正在获取的 URL,并根据需要响应错误、成功案例等。不幸的是,.NET 中的很多 API 不容易测试/伪造:(
My approach to this has been to introduce a wrapper class around
WebClient
(well, I actually usedHttpWebRequest
in the end, asWebClient
did too much in the UI thread...) implementing an interface. I could then create aFakeWebClient
implementingIWebClient
, allowing me to validate the URLs that were being fetched, and responding with errors, success cases etc as desired.It's unfortunate that quite a few APIs in .NET aren't easily testable / fakable :(
这里的方法完全错误。您正在单元测试错误的东西。
您想要做的是将数据解析移至另一个类,并定义一个接口,例如:
然后将其注入到您的类中,并在您的
DownloadStringCompleted
事件中调用iWebParser.Parse(e.Result)
。现在您可以测试 IWebParser 的实现。并更换它。
单元测试并不意味着测试特定于实现的代码。您不妨只使用访问器并测试私有方法!
Completely wrong approach here. You're unit testing the wrong thing.
What you want to do, is to move your parsing of the data out to another class, and define a interface, say:
and then inject that into your class, and in your
DownloadStringCompleted
event, calliWebParser.Parse(e.Result)
.Now you can test your implementations of the IWebParser. And replace it.
Unit Testing isn't meant to test implementation specific code. You might as well just use a accessor and test a private method then!
通常您不应该使用 HTTP 请求进行测试。但无论如何要编写此类测试,最终此链接将帮助您(异步测试):
http ://www.jeff.wilcox.name/2009/03/asynchronous-testing/
Usually you should not test with HTTP requests. But to write such tests anyway eventually this link will help you (asynchronous testing):
http://www.jeff.wilcox.name/2009/03/asynchronous-testing/