markdown 模拟HttpWebRequest

Posted

tags:

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

### dependency
+ NUnit 3
+ NSubstitute
+ FluentAssertions

### production code
``` csharp
public class EZHttp
{
    public string Get(string url)
    {
        var requset = (HttpWebRequest)WebRequest.Create(url);
        requset.Method = "GET";
        requset.Timeout = 1;
        requset.ReadWriteTimeout = 2;
        requset.ContentType = "default";

        using (HttpWebResponse resopnse = (HttpWebResponse)requset.GetResponse())
        using (Stream s = resopnse.GetResponseStream())
        using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
        {
            return sr.ReadToEnd();
        }
    }
}
```

### testing code
``` csharp
[Test()]
public void GetTest_Default_ParametersOfRequestMatchExpected()
{
    // arrange
    var stubResponseString = "response";
    var stubResponseStream = new MemoryStream(Encoding.UTF8.GetBytes(stubResponseString));
    var stubResponse = Substitute.For<HttpWebResponse>();
    stubResponse.GetResponseStream().Returns(stubResponseStream);

    var mockRequest = Substitute.ForPartsOf<HttpWebRequest>();
    mockRequest.When(r => r.GetResponse()).DoNotCallBase();
    mockRequest.GetResponse().Returns(stubResponse);
    // Must init header collection here to avoid NullReferenceExcetpion while try to access ContentType or other properties 
    // depend on private field '_HttpRequestHeaders' in framework.
    // Headers also depend on it, that why we init it via Headers.
    mockRequest.Headers = new WebHeaderCollection();

    var stubUrl = "http://url";
    
    // mock IWebRequestCreate makes WebRequest.Create(url) return mockedRequest,
    // but unable apply to WebRequest.CreateHttp(url)
    var stubRequestCreater = Substitute.For<IWebRequestCreate>();
    stubRequestCreater.Create(Arg.Any<Uri>()).Returns(mockRequest);
    WebRequest.RegisterPrefix(stubUrl, stubRequestCreater);

    var target = new EZHttp();

    string expectedMethod = "GET";
    int expectedTimeout = 1;
    int expectedReadWriteTimeout = 2;
    string expectedContentType = "default";

    // act
    target.Get(stubUrl);

    // assert
    mockRequest.Timeout.Should().Be(expectedTimeout);
    mockRequest.ReadWriteTimeout.Should().Be(expectedReadWriteTimeout);
    mockRequest.ContentType.Should().Be(expectedContentType);
    mockRequest.Method.Should().Be(expectedMethod);
}
```

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

csharp 模拟HttpWebRequest - CustomWebRequest

csharp 模拟HttpWebRequest - SUT

HttpWebRequest 保存Cookies,模拟Session登录

利用HttpWebRequest模拟表单提交

C#,HttpWebRequest模拟发送Post请求

如何使用 HttpWebRequest 模拟浏览器文件上传