【发布时间】:2016-12-16 08:18:07
【问题描述】:
我需要通过 HTTP POST 请求将数据导出为 xml。它是由下面的代码完成的,现在问题是我想通过模拟 http 请求创建单元测试。有人可以帮助我对此进行单元测试吗?
private string WriteBytesToHttp(ExportConfiguration exportConfiguration, byte[] bytes)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(exportConfiguration.Endpoint.Address);
Encoding encoding = exportConfiguration.Format.EncodingCodePage.ToEncoding();
var contentType = string.IsNullOrEmpty(exportConfiguration.Format.ContentType)
? "text/plain"
: exportConfiguration.Format.ContentType;
request.ContentType = contentType;
//request.ContentType = string.Format("{0}; charset={1}", contentType, encoding.HeaderName);
request.ContentLength = bytes.Length;
request.Method = "POST";
if (!(string.IsNullOrEmpty(exportConfiguration.Endpoint.Username) ||
string.IsNullOrEmpty(exportConfiguration.Endpoint.Password)))
{
var creditionStr = string.Format("{0}:{1}", exportConfiguration.Endpoint.Username,
exportConfiguration.Endpoint.Password);
request.Headers.Add("Authorization",
"Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(creditionStr)));
}
Stream newStream = request.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
var streamReader = string.IsNullOrEmpty(response.CharacterSet)
? new StreamReader(responseStream)
: new StreamReader(responseStream, Encoding.GetEncoding(response.CharacterSet));
string responseStr = streamReader.ReadToEnd();
return String.IsNullOrEmpty(responseStr) ? response.StatusCode.ToString() : responseStr;
}
【问题讨论】:
-
您的问题究竟是什么?有什么错误吗?
-
需要通过mock HTTP服务调用为此方法创建unittest
-
我认为您的问题的答案在这里stackoverflow.com/questions/9789944/…
-
@AmalShalika 这不是问题或问题描述。除了过于复杂的代码(为什么不直接使用 HttpClient?)或使用
text/plain而不是text/xml等明显的问题,您是否尝试过使用 y 模拟框架?还是抽象接口背后的请求? -
您提到了 XML,但您的代码没有引用序列化程序或 XML。您无需使用凭据,而是手动编码授权标头。与其模拟 HttpWebRequest 对象,我更关心代码本身
标签: c# asp.net .net unit-testing moq