开发者

Response Object is a null reference in my Controller's action method

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";
     ...
开发者_JAVA技巧     return View();
}

Please advise.

Many thanks.


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
}


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.


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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜