Bullying HttpContext Response.Output with Moq

I used the MvcMockHelpers class found on the Hanselman blog for transmission in the mocked HttpContext. We expanded it somewhat by adding some authentication data that we needed, and for the most part it was great.

The problem is that the context that we pass to the controller has a null value in HttpContext.Response.Output, which raises some exceptions. I'm not sure what to add to make this work.

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 explosion method (which is part of the MVC Contrib project of the XmlResult project):

 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 to the FakeHttpContext method to prevent a null exception when a reference to context.HttpContext.Response.Output is specified?

Clarification: the solution I'm looking for must be made in Moq, not in Rhino. I mentioned Moq in the title of the question, but neglected that in the question of the 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 a null exception. Not sure if this is a good answer for a long time, but it works for now.

+6
c # asp.net-mvc moq mocking
source share
1 answer

In the MvcContrib test, the MvcMockHelps file shows how this is done.

+3
source

All Articles