4

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.

domlao
  • 15,145
  • 32
  • 90
  • 128

2 Answers2

4

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
}
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.

Community
  • 1
  • 1
Jonas Høgh
  • 9,858
  • 1
  • 23
  • 44