How to setup server variables for unit test using moq

asp.net, c#, moq, unit-testing

Solution

There are some misprint on Scott Hanselman's page (lowercase class names). So here is how code should look like (I also changed old `Expect` syntax with new `Setup` syntax):

public static class MvcMockHelpers
{
    public static HttpContextBase FakeHttpContext()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();

        context.Setup(ctx => ctx.Request).Returns(request.Object);
        context.Setup(ctx => ctx.Response).Returns(response.Object);
        context.Setup(ctx => ctx.Session).Returns(session.Object);
        context.Setup(ctx => ctx.Server).Returns(server.Object);

        return context.Object;
    }
}

Back to your case. You see this exception, because when fake HttpContext is created, only its direct properties Request, Response, Session and Server were setup-ed. But you are trying to access property `ServerVariables` of request mock. So, you need to setup some return results for this property. See example how Scott setups request url for request mock:

public static void SetupRequestUrl(this HttpRequestBase request, string url)
{
    if (url == null)
        throw new ArgumentNullException("url");

    var mock = Mock.Get(request);

    mock.Setup(req => req.QueryString)
        .Returns(GetQueryStringParameters(url));
    mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
        .Returns(GetUrlFileName(url));
    mock.Setup(req => req.PathInfo)
        .Returns(string.Empty);
}

Main idea here - you cannot use directly `contextBase.Request.QueryString` you should setup request mock before:

 mock.Setup(req => req.QueryString)
            .Returns(GetQueryStringParameters(url));

Problem

I am using hanselman tutorial to use Moq to create unit tests for my asp.net pages. I wrote the following code to test for ServerVariables in contextbase request class ``` HttpContextBase contextbase = MoqHelper.FakeHttpContext(); contextbase.Request.ServerVariables.Add("AUTH_TYPE","Forms"); <-- error here contextbase.Request.ServerVariables.Add("LOGON_USER", "Tom"); contextbase.Request.ServerVariables.Add("REQUEST_METHOD", "GET"); ``` But I am getting following exception. Please help. System.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object. How do I create unit test to test server variables?

Original source