locked
trying to call controller in unit test RRS feed

  • Question

  • User1642115476 posted

    Hello,

    I'm trying to write some unit tests to test my Web API controller. I'm using a mock System.Web.HttpRequestBase. I'm not sure how to get it to give me a response.

    I started out using a System.Net.WebRequest which could easily get the response with a call to WebRequest.GetResponse() but I had to abandon it since I needed a way of adding data to the data field. After asking around about how to do this, I was told I should use HttpRequestBase instead, which has a QueryString property that returns a NameValueCollection (which is convenient for my data). But HttpRequestBase has no GetResponse() method, so I'm not sure how to use it.

    Can anyone help me please?

    Here is my code so far:


    var mockRequest = new Mock<System.Web.HttpRequestBase>("http://localhost:60209/token");

    var queryString = new System.Collections.Specialized.NameValueCollection
    {
    { "grant_type", "password" },
    { "username", ... },
    { "password", ... }
    };

    mockRequest.Setup(r => r.QueryString).Returns(queryString);

    var mockHttpContext = new Mock<System.Web.HttpContextBase>();
    mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);

    var mockControllerContext = new Mock<ControllerContext>();
    mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);

    var mockSession = new Mock<System.Web.HttpSessionStateBase>();
    mockHttpContext.Setup(c => c.Session).Returns(mockSession.Object);

    This is supposed to mimick this AJAX call:


    $.ajax({
    url: "http://localhost:60209/token",
    type: "POST",
    headers: {
    Accept: "application/json"
    },
    ContentType: "application/x-www-form-urlencoded",
    data: {
    grant_type: "password",
    username: ...,
    password: ..."
    }
    }).done(function(data)
    {
    ...
    });

    Thursday, December 8, 2016 12:02 AM

All replies