csharp 模拟HttpWebRequest - CustomWebRequest

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 模拟HttpWebRequest - CustomWebRequest相关的知识,希望对你有一定的参考价值。

using Moq;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace LeeSoft.TestUtils
{
    public class CustomWebRequest : IWebRequestCreate
    {
        public static WebRequest NextRequest { get; set; }

        public WebRequest Create(Uri uri)
        {
            return NextRequest;
        }

        public static HttpWebRequest CreateRequestWithResponseCode(HttpStatusCode httpStatusCode)
        {
            var response = new Mock<HttpWebResponse>(MockBehavior.Loose);
            response.Setup(c => c.StatusCode).Returns(httpStatusCode);

            var request = new Mock<HttpWebRequest>();
            request.Setup(s => s.GetResponse()).Returns(response.Object);
            NextRequest = request.Object;
            return request.Object;
        }

        public static HttpWebRequest CreateRequestWithResponse(string responseContent)
        {
            var response = new Mock<HttpWebResponse>(MockBehavior.Loose);
            var responseStream = new MemoryStream(Encoding.UTF8.GetBytes(responseContent));
            response.Setup(c => c.StatusCode).Returns(HttpStatusCode.OK);
            response.Setup(c => c.GetResponseStream()).Returns(responseStream);

            var request = new Mock<HttpWebRequest>();
            request.Setup(s => s.GetResponse()).Returns(response.Object);
            NextRequest = request.Object;

            return request.Object;
        }
    }
}

以上是关于csharp 模拟HttpWebRequest - CustomWebRequest的主要内容,如果未能解决你的问题,请参考以下文章

csharp 模拟HttpWebRequest - SUT

csharp HttpWebRequest的提交后数据

markdown 模拟HttpWebRequest

HttpWebRequest 保存Cookies,模拟Session登录

利用HttpWebRequest模拟表单提交

C#,HttpWebRequest模拟发送Post请求