Third party REST interface mocking, mocking HttpWebRequest and HttpWebResponse

Hello all, We have a third party component with a REST interface. We have abstracted the calls away in our own methods. I am trying to UNIT test my abstraction layer methods and I am trying to Mock (using Moq) the REST call, but I have not figure out how to do that. Anyone done anything like that before? this is .NET code.

Answers

  • This heavily depends on what your method signatures are but if you want to mock a HttpWebResponse you can use something like this. (This is assuming the code is getting the resposne from a GetResponseStream()) string expectedMessage = "Expected Response"; using (var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes(expectedMessage))) using (var streamReader = new StreamReader(expectedStream)) { Mock

    response = new Mock

    (); response.Setup(i => i.GetResponseStream()).Returns(expectedStream); var actualStream = response.Object.GetResponseStream(); string actualMessage = streamReader.ReadToEnd(); Assert.AreEqual(expectedStream, actualStream); Assert.AreEqual(expectedMessage, actualMessage); }