【问题标题】:c# - Unit testing HTTPWebRequestc# - 单元测试 HTTPWebRequest
【发布时间】:2019-01-14 18:29:18
【问题描述】:

我有一个代码来发出 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();

                    }
                }


            }
}

【问题讨论】:

  • “我希望在不运行任何服务器的情况下测试响应” - 我正在努力看看它是如何工作的。你到底想在这里测试什么?
  • 我正在使用 httpwebrequest 从工作站向服务器发送数据,服务器端的 wcf 服务接收该数据。我想在我的本地机器上测试上述方法,而不运行 wcf 服务,比如返回自定义响应。这可能吗?
  • 我相信您正在寻找一种模拟响应的方法?如果您在 Google 上搜索该词,它是否有助于引导您?
  • 您可以在示例中添加使用 out 参数 response 的代码吗?

标签: c# .net unit-testing httpwebrequest moq


【解决方案1】:

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

//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

欢迎star/fork我的仓库
https://github.com/Flithor/CSharpInteractive_Mini_HttpRequest_Responder

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多