c# - c# - 单元测试 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
欢迎star/fork我的存储库
https://github.com/Flithor/CSharpInteractive_Mini_HttpRequest_Responder
推荐阅读
- php - 如何在 API 资源中使用条件关系?
- sql - 从表中删除重复项并将引用行重新链接到新的主数据
- scala - json4s如何使用DefaultFormats对json进行序列化和反序列化?
- java - 未使用 SharedPreferences 存储的字符串
- laravel - Laravel Nova 多对多资源失败
- android - 无法运行我的 react-native 应用程序,因为我遇到了错误
- drupal - #autocomplete_path 在 Drupal 7 中触发焦点
- java - 递归替换二维数组中的内部数组
- python - 在多个 CSV 文件中搜索特定行并保存特定列以及日期信息
- angular - 运行 ng build --prod 时传单标记图标 url 编译错误