单元测试 HTTPWebRequest



我有一个代码来发出HTTP web请求并获得响应。如何对调用方法进行单元测试,我发现了一些与单元测试 HTTP Web 请求和响应相关的链接,但它们让我感到困惑。

我希望在不运行任何服务器的情况下测试响应。

单元测试代码:

        [TestMethod]
        public void TestMethod()
        {
            string request = "request content";
            WebServiceClass webServiceClass = new WebServiceClass();
            string actual_response;
            webServiceClass.InvokeService               
       (request,"POST","application/json","/invoke",out actual_response);
            string expected_response="response content";
            Assert.AreEqual(actual_response, expected_response);
        }

实际代码:

class WebServiceClass {
 private HttpWebRequest BuildHttpRequest(String requestMethod, String contentType,String uriExtension, int dataBytes)
        {
            String composeUrl = webServiceURL + "/" + uriExtension;
            Uri srvUri = new Uri(composeUrl);
            HttpWebRequest httprequest = (HttpWebRequest)HttpWebRequest.Create(srvUri);
            httprequest.Method = requestMethod;
            httprequest.ContentType = contentType;
            httprequest.KeepAlive = false;
            httprequest.Timeout = webSrvTimeOut;
            httprequest.ContentLength = dataBytes;
            System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            httprequest.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
            return httprequest;
        }

        public void InvokeService(String request, String requestMethod, String contentType,String uriExtension, out String response)
        {
            Encoding encoding = new UTF8Encoding();
            String serviceResponse = String.Empty;
            byte[] dataBytes = encoding.GetBytes(request);
            try
            {
                int dataLength = dataBytes.Length;
                HttpWebRequest httprequest = BuildHttpRequest(requestMethod, contentType, uriExtension, dataLength);
                using (StreamWriter writes = new StreamWriter(httprequest.GetRequestStream()))
                {
                    writes.Write(request);
                }
                using (HttpWebResponse httpresponse = (HttpWebResponse)httprequest.GetResponse())
                {
                    String httpstatuscode = httpresponse.StatusCode.ToString();
                    using (StreamReader reader = new StreamReader(httpresponse.GetResponseStream(), Encoding.UTF8))
                    {
                        serviceResponse = reader.ReadToEnd().ToString();
                    }
                }

            }
}

也许晚了,但我认为这就是你想要的。

//Copy Code and paste in C# Interactive Window
//(Existed in VS 2015+, "View->Other Window->C# Interactive")
//If you writen an http request and need a response test
//but the target API hasn't complated
//you can use this code to built a simple responder in C# Interactive window
//without to create a new webapi project for testing!
using System.Net;
var l = new HttpListener();
l.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
l.Prefixes.Add("http://localhost:8080/API/XXXX/");//ATTACTION: Uri should end with "/"
//more target url
var t = Task.Run(() =>
{
    Print("START!");
    l.Start();
    try
    {
        while (l.IsListening)
        {
            HttpListenerContext ctx = l.GetContext();//here for waiting
            Print(new StreamReader(ctx.Request.InputStream).ReadToEnd());
            ////Set Response here
            //ctx.Response.StatusCode = 200;
            //ctx.Response.OutputStream.Write("true".Select(c => (byte)c).ToArray(), 0, 4);
            ctx.Response.Close();//"Close" for return response
        }
    }
    catch { Print("STOP!"); }
});
//l.Stop(); //Call this method to stop HttpListener

欢迎使用星标/分叉我的仓库
https://github.com/Flithor/CSharpInteractive_Mini_HttpRequest_Responder

相关内容

  • 没有找到相关文章

最新更新