Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create mock HTTP post request with a JSON body using Moq

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.

like image 407
D3v Avatar asked Dec 11 '22 12:12

D3v


1 Answers

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 };
like image 67
ladeangel Avatar answered Dec 29 '22 11:12

ladeangel