I have a method in a Class and would like build a unit test on it. The method just send data via a HttpWebRequest to a server.
As I would like to test without the server, I found a way here (Is it possible to mock out a .NET HttpWebResponse?) to mock the HttpWebResquest/httpWebResponse. However, I do not know how to make my code call the mocked HttpWebResquest/httpWebResponse object.
Here is my Code:
public long PostRequest(Uri uri,string data)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
System.Text.UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(data);
using (Stream requestStream = request.GetRequestStream())
{
//Transmit data
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
}
//Get the Response from the server
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
{
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
}
}
return request.ContentLength;
}
catch (Exception e)
{
throw e;
}
}
How could I make my code call the mocked HttpWebResquest/httpWebResponse?
Aucun commentaire:
Enregistrer un commentaire