I want to test this method using Moq. Can someone tell me how to do this? I am attaching the userid and value in the query string. How to mimic this in moq. The name of the class is RestClient.cs. I have created an interface called IRestClient. public interface IRestClient { string MakeRequest(string userID, string value ); }
This is the makeRequest method of the RestClient class
public string MakeRequest(string userId,string value)
{
Logger.Info("Entering method MakeRequest()." + "Input Parameter: " + userId+Constant.NewLine+value);
string strResponseValue = string.Empty;
// The HttpWebRequest class allows you to programatically make web requests against an HTTP server.
// create the WebRequest instantiated for making the request to the specified URI.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constant.webServerURI+"?id="+userId + Constant.UserValueAppend + value);
//Gets or sets the method for the request.(Overrides WebRequest.Method.)
request.Method = httpMethod.ToString();
//Initially response from webserver is set to null.
HttpWebResponse response = null;
try
{
// Get the response in the response object of type HttpWebResponse
// The request object of HttpWebRequest class is used to "get" the response (GetResponse()) from WebServer and store it in the response object
response = (HttpWebResponse)request.GetResponse();
// We check that the response StatusCode is good and we can proceed
if (response.StatusCode != HttpStatusCode.OK)
{
Logger.Error("Error" + response.StatusCode.ToString());
throw new ApplicationException(Constant.ErrorDisplay + response.StatusCode.ToString());
}
// Process the response string
// We obtain the ResponseStream from the webserver using "get" (GetResponseStream())
// The Stream Class provides a generic view of a sequence of bytes
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
//read the stream and store it in string strResponseValue
strResponseValue = reader.ReadToEnd();
}//End of StreamReader
}
}//End of using ResponseStream
}// End of using Response
catch (Exception ex)
{
Logger.Error("Error" + ex.Message.ToString());
strResponseValue = ("Error " + ex.Message.ToString());
}
finally
{
if (response != null)
{
((IDisposable)response).Dispose();
}
}
//return the string strResponseValue
Logger.Info("Leaving method MakeRequest." + "Output parameter: " + strResponseValue);
return strResponseValue;
}
This is my attempt at creating the moq in my unittest class called RestClientTests.cs
[TestMethod]
public void TestMethod1()
{
var expected = "response content";
var expectedBytes = Encoding.UTF8.GetBytes(expected);
var responseStream = new MemoryStream();
responseStream.Write(expectedBytes, 0, expectedBytes.Length);
responseStream.Seek(0, SeekOrigin.Begin);
var mockRestClient = new Mock<IRestClient>();
var mockHttpRequest = new Mock<HttpWebRequest>();
var response = new Mock<HttpWebResponse>();
response.Setup(c => c.GetResponseStream()).Returns(responseStream);
mockHttpRequest.Setup(c => c.GetResponse()).Returns(response.Object);
var factory = new Mock<IHttpWebRequestFactory>();
factory.Setup(c => c.Create(It.IsAny<string>())).Returns(mockHttpRequest.Object);
var actualRequest = factory.Object.Create("http://localhost:8080");
actualRequest.Method = WebRequestMethods.Http.Get;
string actual;
using (var httpWebResponse = (HttpWebResponse)actualRequest.GetResponse())
{
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
actual = streamReader.ReadToEnd();
}
}
mockRestClient.Setup(moq => moq.MakeRequest("xxx", "s")).Returns(actual);
}
My IhttpWebRequestFactory interface looks like this:
interface IHttpWebRequestFactory
{
HttpWebRequest Create(string uri);
}
I am not sure how to test this
Your current test method makes no sense for me.
If you are testing your RestClient
class, which implements IRestClient
, you don't need to mock IRestClient
itself. You need to mock all external dependencies instead - you've already created mock for IHttpWebRequestFactory
, now you need to inject it into tested object. I don't see rest of your class, but I assume that your WebRequest
object is of type IHttpWebRequestFactory
- you need to assign your factory mock to it.
Now you need to define your test cases. I can quickly see following (but you can have more of cause):
Now for each test case you need to prepare proper setup and validation. For example, for 1st you need your mocked factory to return mocked request which will return mocked response with not OK result code. Now you need to call your actual object. As a validation you need to check that ApplicationException is thrown and all your mocks were actually called.
Ok, this is partial setup for 2nd test case. It will prepare mocked factory which returns mocked request which returns mocked response with OK code:
var response = new Mock<HttpWebResponse>();
response.SetupGet(c => c.StatusCode).Returns( HttpStatusCode.OK);
var mockHttpRequest = new Mock<HttpWebRequest>();
mockHttpRequest.Setup(c => c.GetResponse()).Returns(response.Object);
var factory = new Mock<IHttpWebRequestFactory>();
factory.Setup(c => c.Create(It.IsAny<string>))).Returns(mockHttpRequest.Object);