Mocking a HttpContext Response.Output with Moq

僤鯓⒐⒋嵵緔 提交于 2019-12-31 22:39:31

问题


I've been using the MvcMockHelpers class found at Hanselman's blog for passing in a mocked HttpContext. We extended it somewhat to add some authentication data we needed and for the most part this has been great.

The issue we are having is that the context we are giving to the controller has a null value in the HttpContext.Response.Output, which is causing some exceptions to be thrown. I'm not sure what to add to get this working.

Here is the existing FakeHttpConext() method:

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>();

    // Our identity additions ...
    var user = new Mock<IPrincipal>();
    OurIdentity identity = (OurIdentity)Thread.CurrentPrincipal.Identity;

    context.Expect(ctx => ctx.Request).Returns(request.Object);
    context.Expect(ctx => ctx.Response).Returns(response.Object);
    context.Expect(ctx => ctx.Session).Returns(session.Object);
    context.Expect(ctx => ctx.Server).Returns(server.Object);
    context.Expect(ctx => ctx.User).Returns(user.Object);
    context.Expect(ctx => ctx.User.Identity).Returns(identity);
    return context.Object;
}

Here is the exploding method (which is part of the MVC Contrib project's XmlResult):

public override void ExecuteResult(ControllerContext context)
{
    if (_objectToSerialize != null)
    {
       var xs = new XmlSerializer(_objectToSerialize.GetType());
       context.HttpContext.Response.ContentType = "text/xml";
       xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize);
    }
}

What do I need to add in the FakeHttpContext method to prevent the null exception when the context.HttpContext.Response.Output is referenced?

Clarification: The solution I'm looking for needs to be done in Moq, not Rhino. I mentioned Moq in the question title but neglected that in question body. Sorry for any confusion.

Resolution I added the following two lines of code to the FakeHttpContext() method:

var writer = new StringWriter();
context.Expect(ctx => ctx.Response.Output).Returns(writer);

This prevents the null exception. Not sure if its a good answer long term, but it works for now.


回答1:


In the Tests for MvcContrib the file MvcMockHelps shows how it is done.



来源:https://stackoverflow.com/questions/542132/mocking-a-httpcontext-response-output-with-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!