如何创建一个模拟HttpWebRequest和HttpWebResponse对象

时间:2013-04-22 23:24:07

标签: c# unit-testing

如何创建模拟HttpWebRequest和HttpWebResponse对象 我正在尝试对以下代码进行单元测试

HttpWebrequest request;   

if (null != request)
{                         
    var response = (HttpWebResponse)request.GetResponse();
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        jsonResult = sr.ReadToEnd();
    }

    var myRecords = SerializationHelper.Deserialize<Records>(jsonResult);
}

8 个答案:

答案 0 :(得分:2)

你不能为HttpWebResponse创建模拟,而不是模拟出HttpWebResponse在接口后面进行包装调用,并模拟该接口。

答案 1 :(得分:2)

这是一个老问题,但也许对某人有用。改编自this question in msdn

private static WebResponse CreateWebResponse(HttpStatusCode httpStatus, MemoryStream responseObject)
{
  TcpListener l = new TcpListener(IPAddress.Loopback, 0);
  l.Start();
  int port = ((IPEndPoint)l.LocalEndpoint).Port;
  l.Stop();

  // Create a listener.
  string prefix = "http://localhost:" + port + "/";
  HttpListener listener = new HttpListener();
  listener.Prefixes.Add(prefix);
  listener.Start();
  try
  {
    listener.BeginGetContext((ar) =>
    {
      HttpListenerContext context = listener.EndGetContext(ar);
      HttpListenerRequest request = context.Request;

      // Obtain a response object.
      HttpListenerResponse response = context.Response;

      response.StatusCode = (int)httpStatus;

      // Construct a response.
      if (responseObject != null)
      {
        byte[] buffer = responseObject.ToArray();

        // Get a response stream and write the response to it.
        Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
      }

      response.Close();
    }, null);

    WebClient client = new WebClient();
    try
    {
      WebRequest request = WebRequest.Create(prefix);
      request.Timeout = 30000;
      return request.GetResponse();
    }
    catch (WebException e)
    {
      return e.Response;
    }
  }
  finally
  {
    listener.Stop();
  }

  return null;
}

在这里,您可以在响应对象中写下您想要的任何内容,或者将其保留为空。

答案 2 :(得分:1)

在我一直在研究的项目中,我需要在ASMX Web服务中做一些重写,该服务仅在生产中抛出错误,以找出服务实际上回流的XML。为了做到这一点,我不得不创建一个新的HttpWebResponse对象。基本技巧是使用 Activator.CreateInstance (绕过了不推荐使用构造函数的事实)。在下面的例子中,我正在利用这样一个事实,即我只是克隆现有的HttpWebResponse对象并重置流,但是从头开始创建一个这个技术是一样的。

    string sLastXML;

    public string LastXML
    {
        get
        {
            return sLastXML;
        }
    }

    protected override System.Net.WebResponse GetWebResponse(System.Net.WebRequest request)
    {
        // Get the XML Returned
        System.Net.HttpWebResponse oResponse = (System.Net.HttpWebResponse)request.GetResponse();
        System.IO.Stream oStream = oResponse.GetResponseStream();
        byte[] inStream = new byte[oResponse.ContentLength];
        int iActual = 0;
        while (iActual < oResponse.ContentLength)
        {
            iActual += oStream.Read(inStream, iActual, (int)oResponse.ContentLength - iActual);
        }
        sLastXML = System.Text.Encoding.Default.GetString(inStream);

        // Create new stream
        System.IO.MemoryStream oNewStream = new System.IO.MemoryStream();
        oNewStream.Write(inStream, 0, (int)oResponse.ContentLength);
        oNewStream.Position = 0;

        // Create new response object
        System.Net.HttpWebResponse oNewResponse = (System.Net.HttpWebResponse)System.Activator.CreateInstance(typeof(System.Net.HttpWebResponse));
        System.Reflection.PropertyInfo oInfo = oNewResponse.GetType().GetProperty("ResponseStream", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oInfo.SetValue(oNewResponse,oNewStream);
        System.Reflection.FieldInfo oFInfo = oNewResponse.GetType().GetField("m_HttpResponseHeaders", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_ContentLength", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_Verb", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_StatusCode", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_StatusDescription", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_IsMutuallyAuthenticated", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_IsVersionHttp11", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_MediaType", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_Uri", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));
        oFInfo = oNewResponse.GetType().GetField("m_UsesProxySemantics", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy);
        oFInfo.SetValue(oNewResponse, oFInfo.GetValue(oResponse));

        oNewResponse.Cookies = oResponse.Cookies;

        return oNewResponse;


    }

答案 3 :(得分:1)

您可以使用反射重写需要调整的响应字段以创建模拟响应。以下是使用状态码429创建响应的示例:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
statusCode = (int)response.StatusCode;
ActivateCallback(responseCallback, response, url, string.Empty);

var fieldStatusCode = response.GetType().GetField("m_StatusCode", 
                                                   BindingFlags.Public | 
                                                   BindingFlags.NonPublic | 
                                                   BindingFlags.Instance);
var statusCodeNew = (HttpStatusCode)409;
fieldStatusCode.SetValue(response, statusCodeNew);
string responceBody = "{\"error\":{\"code\":\"AF429\",\"message\":\"Too many requests. Method=GetContents, PublisherId=00000000-0000-0000-0000-000000000000\"}}";

var propStream = response.GetType().GetField("m_ConnectStream", 
                                              BindingFlags.Public | 
                                              BindingFlags.NonPublic | 
                                              BindingFlags.Instance);

System.IO.MemoryStream ms = new System.IO.MemoryStream(
                           System.Text.Encoding.UTF8.GetBytes(responceBody));
propStream.SetValue(response, ms);
ms.Position = 0;

答案 4 :(得分:0)

我没有亲自使用它,但Moles框架应该让你做你想做的事情。有关拦截对DateTime.Now的调用的示例,请参阅here

答案 5 :(得分:0)

模拟HttpResponse可能如下所示:

public SenHttpMockResponse(HttpListenerContext context)
{
   HttpListenerResponse response = context.Response;
   response.Headers.Add("Content-type", @"application/json");
   JObject message = JObject.Parse(@"{'SomeParameterName':'ParameterValue'}");
   StreamWriter writer = new StreamWriter(response.OutputStream);
   writer.Write(message);
   writer.Close();
}

默认情况下,响应代码在这种情况下为200,但您也可以使用Response.StatusCode = 400;

进行调整

要模拟请求,您可以使用例如调试工具。例如Firefox addon HttpRequester非常酷。你可以提出所有类型的请求,你也会看到你的回复。我会说这是一个方便的东西

答案 6 :(得分:0)

您还可以使用SOAP格式化程序构建模拟HttpWebRequest。首先捕获要作为字符串模拟的HttpWebRequest,然后您可以在单元测试中自定义它,并通过反序列化字符串来重建HttpWebRequest。

以下是一个例子:

    static void Main(string[] args)
    {
        SoapFormatter formatter = new SoapFormatter();

        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        HttpWebResponse resp = (HttpWebResponse)myReq.GetResponse();

        // save this soapRequest as a string and customize it for your mocking up
        MemoryStream target = new MemoryStream();
        using(target)
        {
            formatter.Serialize(target, resp);
        }
        string soapRequest = Encoding.UTF8.GetString(target.GetBuffer());

        // now you can use the string to reconstruct the object from the string without needing anything special (other than substituting your own values into the XML)
        HttpWebResponse myMockedObject = (HttpWebResponse)formatter.Deserialize(
            new MemoryStream(Encoding.UTF8.GetBytes(soapRequest)));
    }

答案 7 :(得分:0)

我认为包装和抽象是最正确的方法。 但是,这是我的 hacky 解决方案。

只需使用序列化构造函数重载(它也已过时,但它会生成可以抑制的警告)并覆盖您需要更改的方法。

public class FakeHttpWebRequest : HttpWebRequest
{
    private static readonly SerializationInfo SerializationInfo = GetSerializationInfo();
    private readonly WebResponse response;

    public FakeHttpWebRequest(WebResponse response)
    #pragma warning disable CS0618 // Type or member is obsolete
        : base(
              SerializationInfo,
              new StreamingContext())
    #pragma warning restore CS0618 // Type or member is obsolete

    {
        this.response = response;
    }

    public override WebResponse GetResponse()
    {
        return response;
    }

    public override Stream GetRequestStream()
    {
        return new MemoryStream();
    }

    private static SerializationInfo GetSerializationInfo()
    {
        // dummy data required for HttpWebRequest() constructor
        var serializationInfo = new SerializationInfo(typeof(HttpWebRequest), new FormatterConverter());
        serializationInfo.AddValue("_HttpRequestHeaders", new WebHeaderCollection(), typeof(WebHeaderCollection));
        serializationInfo.AddValue("_Proxy", null, typeof(IWebProxy));
        serializationInfo.AddValue("_KeepAlive", false);
        serializationInfo.AddValue("_Pipelined", false);
        serializationInfo.AddValue("_AllowAutoRedirect", false);
        serializationInfo.AddValue("_AllowWriteStreamBuffering", false);
        serializationInfo.AddValue("_HttpWriteMode", 0);
        serializationInfo.AddValue("_MaximumAllowedRedirections", 0);
        serializationInfo.AddValue("_AutoRedirects", 0);
        serializationInfo.AddValue("_Timeout", 0);
        serializationInfo.AddValue("_ContentLength", (long)0);
        serializationInfo.AddValue("_MediaType", "");
        serializationInfo.AddValue("_OriginVerb", "GET");
        serializationInfo.AddValue("_ConnectionGroupName", "");
        serializationInfo.AddValue("_Version", new Version(1, 0), typeof(Version));
        serializationInfo.AddValue("_OriginUri", new Uri("https://fake.uri"), typeof(Uri));

        return serializationInfo;
    }
}


public class FakeHttpWebResponse : HttpWebResponse
{
    private static readonly SerializationInfo SerializationInfo = GetSerializationInfo();
    private readonly Stream responseStream;

    public FakeHttpWebResponse(HttpStatusCode statusCode, Stream responseStream)
    #pragma warning disable CS0618 // Type or member is obsolete
        : base(
              SerializationInfo,
              new StreamingContext())
    #pragma warning restore CS0618 // Type or member is obsolete
    {
        this.StatusCode = statusCode;
        this.responseStream = responseStream;
    }

    public override HttpStatusCode StatusCode { get; }

    public override Stream GetResponseStream()
    {
        return responseStream;
    }

    private static SerializationInfo GetSerializationInfo()
    {
        // dummy data required for HttpWebResponse() constructor
        var serializationInfo = new SerializationInfo(typeof(HttpWebResponse), new FormatterConverter());
        serializationInfo.AddValue("m_HttpResponseHeaders", new WebHeaderCollection(), typeof(WebHeaderCollection));
        serializationInfo.AddValue("m_Uri", new Uri("https://fake.uri"), typeof(Uri));
        serializationInfo.AddValue("m_Certificate", null, typeof(System.Security.Cryptography.X509Certificates.X509Certificate));
        serializationInfo.AddValue("m_Version", new Version(), typeof(Version));
        serializationInfo.AddValue("m_StatusCode", (int)HttpStatusCode.HttpVersionNotSupported);
        serializationInfo.AddValue("m_ContentLength", (long)0);
        serializationInfo.AddValue("m_Verb", "GET");
        serializationInfo.AddValue("m_StatusDescription", "");
        serializationInfo.AddValue("m_MediaType", "");
        return serializationInfo;
    }
}

最后,在您的产品代码中提供一种将 WebRequest 创建替换为您的测试代码的方法。

    /// <summary>
    /// Delegate to create new web request. Can be set to mock actual requests.
    /// </summary>
    public Func<string, WebRequest> CreateWebRequest { get; set; } = url => WebRequest.Create(url);

并从您的生产代码中使用此委托,而不是直接使用 WebRequest.Create()。

在测试中,您可以将此委托设置为您需要的任何内容。