我有一个集成测试,从第三方服务器上获取了一些 json 的结果。真的很简单,效果很好。
我希望停止实际上打击这个服务器,并使用 Moq
(或任何 Mocking 库,如注入等)劫持和强制返回结果。
这可能吗?
下面是一些示例代码:-
public Foo GoGetSomeJsonForMePleaseKThxBai()
{
// prep stuff ...
// Now get json please.
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("Http://some.fancypants.site/api/hiThere);
httpWebRequest.Method = WebRequestMethods.Http.Get;
string responseText;
using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
json = streamReader.ReadToEnd().ToLowerInvariant();
}
}
// Check the value of the json... etc..
}
当然,这个方法是从我的测试中调用的。
I was thinking that maybe I need to pass into this method (or a property of the class?) a mocked httpWebResponse
or something but wasn't too sure if this was the way. Also, the response is a output from an httpWebRequest.GetResponse()
method .. so maybe I just need to pass in a mocked HttpWebRequest
?.
任何建议与一些示例代码将是最受欢迎的!