7

I'm developing a webapp using ASP.NET MVC and C#. And I'm creating a unit test for this webapp using NUnit and Rhino Mock. My problem is that I have a Response object in my controller's action method and when I execute my unit test my test is failing because the Response object is a null reference.

Do I need to separate this Response object call in my actions or there is a better way to resolve this?

public ActionResult Login( string user, string password )
{
     Response.Cookies[ "cookie" ].Value = "ck";
     ...
     return View();
}

Please advise.

Many thanks.

3 Answers 3

10

What the controller really lacks is its HttpContext. In a test method it should be added explicitly if needed:

[Test]
public void TestMethod()
{
    // Assume the controller is created once for all tests in a setup method
    _controller.ControllerContext.HttpContext = new DefaultHttpContext();
    var result = _controller.Login("username", "verySaf3Passw0rd");

    // Asserts here
}
Sign up to request clarification or add additional context in comments.

1 Comment

This approach worked for me even though I was looking for some way to set request HTTP headers: StringValues stringValues = new StringValues(headerValue); DefaultHttpContext context = new DefaultHttpContext(); context.Request.Headers[headerName] = stringValues; _controller.ControllerContext.HttpContext = context;
3

This is one of the annoying points where ASP.NET MVC is not as testable and loosely coupled as it could be. See this question for some suggestions how to mock the HTTP context objects.

Comments

0

I ended up creating a real response that my mock context returns like this...

    Mock<HttpSessionStateBase> mockSession;
    Mock<ControllerContext> mockContext;
    Mock<ISessionProvider> mockSessionProvider;
    HttpResponse testResponse;
    MyController controller;

    [TestInitialize]
    public void Initialize()
    {
        testResponse = new HttpResponse(TextWriter.Null);
        mockContext = new Mock<ControllerContext>();
        mockSession = new Mock<HttpSessionStateBase>();
        mockContext.Setup(x => x.HttpContext.Session).Returns(mockSession.Object);
        mockContext.Setup(x => x.HttpContext.Response).Returns(new HttpResponseWrapper(testResponse));
        controller = new MyController();
        controller.ControllerContext = mockContext.Object;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.