[英]Unit testing a method with HTTP post request by mocking HttpWebRequest
我需要通過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;
}
我使用MockHttpServer服務來模擬HttpWebRequest請求和響應。 因此,我將能夠對代碼進行單元測試,而無需創建用於創建HttpWebReqeust的提取工廠。 下面是使用MockHttpService的單元測試代碼。
[Test]
public void Http_Transport_ExportPG_Order()
{
var port = GetFreeTcpPort();
var url = string.Format("http://localhost:{0}/api/ifs/import", port);
....................
using (new MockServer(port, "api/ifs/import", (req, rsp, prm) => "Result Body"))
{
Wait.For<ExportDispatched>(() =>
Bus.Raise(new PutawayPlacedConfirmed(1, 2, 3)), null);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.