在 Windows Phone 7 中对 WebClient 进行单元测试

发布于 2024-12-12 07:56:32 字数 128 浏览 0 评论 0原文

我的应用程序中有一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒中人 2024-12-19 07:56:32

我的方法是围绕 WebClient 引入一个包装类(好吧,我实际上最终使用了 HttpWebRequest,因为 WebClient 做了太多的事情在 UI 线程中...) 实现一个接口。然后,我可以创建一个实现 IWebClientFakeWebClient,允许我验证正在获取的 URL,并根据需要响应错误、成功案例等。

不幸的是,.NET 中的很多 API 不容易测试/伪造:(

My approach to this has been to introduce a wrapper class around WebClient (well, I actually used HttpWebRequest in the end, as WebClient did too much in the UI thread...) implementing an interface. I could then create a FakeWebClient implementing IWebClient, 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 :(

倾城花音 2024-12-19 07:56:32

这里的方法完全错误。您正在单元测试错误的东西。

您想要做的是将数据解析移至另一个类,并定义一个接口,例如:

interface IWebParser { MyResult Parse(string input); }

然后将其注入到您的类中,并在您的 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:

interface IWebParser { MyResult Parse(string input); }

and then inject that into your class, and in your DownloadStringCompleted event, call iWebParser.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!

归途 2024-12-19 07:56:32

通常您不应该使用 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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文