I'm trying to do basically what the title says in order to unit test my api controller, but I have problems finding the proper way and can't afford spending too much time on this. Here is my code.
[TestMethod]
public void Should_return_a_valid_json_result()
{
    // Arrange
    Search search = new Search();
    search.Area = "test";
    string json = JsonConvert.SerializeObject(search);
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    request.Setup(r => r.HttpMethod).Returns("POST");
    request.Setup(r => r.InputStream.ToString()).Returns(json);
    context.Setup(c => c.Request).Returns(request.Object);
    var controller = new UserController();
    controller.ControllerContext = new HttpControllerContext() {  RequestContext = context };
   //more code
}
Last line returns Error CS0029 Cannot implicitly convert type 'Moq.Mock System.Web.HttpContextBase' to 'System.Web.Http.Controllers.HttpRequestContext'.
I am also not sure about the Moq syntax I should use, other questions,examples and Moq Documentation didn't help me much.
I'm using this approach
        var json = JsonConvert.SerializeObject(request);
        var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
        var httpContext = new DefaultHttpContext()
                              {
                                Request = { Body = stream, ContentLength = stream.Length }
                              };
        var controllerContext = new ControllerContext { HttpContext = httpContext };            
        var controller = new Your_Controller(logic, logger) { ControllerContext = controllerContext };
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With