从 WebRequest 模拟 WebResponse [英] Mocking WebResponse's from a WebRequest

查看:48
本文介绍了从 WebRequest 模拟 WebResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于开始忙于创建一些与 RESTful Web 界面一起使用的应用程序,但是,我担心每次按 F5 运行一系列测试时我都会敲打他们的服务器..

I have finally started messing around with creating some apps that work with RESTful web interfaces, however, I am concerned that I am hammering their servers every time I hit F5 to run a series of tests..

基本上,我需要获得一系列网络响应,以便我可以测试我是否正确解析了不同的响应,而不是每次都访问他们的服务器,我想我可以这样做一次,保存 XML,然后在本地工作.

Basically, I need to get a series of web responses so I can test I am parsing the varying responses correctly, rather than hit their servers every time, I thought I could do this once, save the XML and then work locally.

但是,我不知道如何模拟"一个 WebResponse,因为 (AFAIK) 它们只能由 WebRequest.GetResponse

However, I don't see how I can "mock" a WebResponse, since (AFAIK) they can only be instantiated by WebRequest.GetResponse

你们是如何嘲笑这种事情的?你?我真的不喜欢我正在敲打他们的服务器的事实:S 我不想太多更改代码,但我希望有一种优雅的方式来做到这一点..

How do you guys go about mocking this sort of thing? Do you? I just really don't like the fact I am hammering their servers :S I dont want to change the code too much, but I expect there is a elegant way of doing this..

Will 的回答是我需要的一记耳光,我知道我错过了一个基本点!

Will's answer was the slap in the face I needed, I knew I was missing a fundamental point!

  • 创建一个接口,该接口将返回一个代表 XML 的代理对象.
  • 实现该接口两次,一次使用 WebRequest,另一次实现静态响应".
  • 接口实现然后根据响应或静态 XML 实例化返回类型.
  • 然后,您可以在测试或生产时将所需的类传递给服务层.

等我敲完代码,我会粘贴一些示例.

Once I have the code knocked up, I'll paste some samples.

推荐答案

我在寻找完全相同的事情时发现了这个问题.无法在任何地方找到答案,但经过更多挖掘后发现 .Net Framework 已内置对此的支持.

I found this question while looking to do exactly the same thing. Couldn't find an answer anywhere, but after a bit more digging found that the .Net Framework has built in support for this.

您可以使用 WebRequest.RegisterPrefix 注册一个工厂对象,当使用该前缀(或 url)时,WebRequest.Create 将调用该对象.工厂对象必须实现 IWebRequestCreate,它有一个返回 WebRequest 的方法 Create.在这里您可以返回您的模拟 WebRequest.

You can register a factory object with WebRequest.RegisterPrefix which WebRequest.Create will call when using that prefix (or url). The factory object must implement IWebRequestCreate which has a single method Create which returns a WebRequest. Here you can return your mock WebRequest.

我已经把一些示例代码放在http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/

I've put some sample code up at http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/

这篇关于从 WebRequest 模拟 WebResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆