OWASP O2 Platform Blog

Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq)

I just added support to O2 Platform for easy mocking of HttpContext, HttpRequest and HttpResponse (very useful for ASP.NET Unit Test and Security Scripting). 

The solution is based on the Moq Mocking framework and on the great info provided in this , this and this posts

As an example, this is how the Input Stream of the HttpRequest can be maniplated (same logic for the OutputStream):

var mockHttpContext = new API_Moq_HttpContext();
var httpContext = mockHttpContext.httpContext();

httpContext.request_Write("   this is a web page".line());  

return httpContext.request_Read();

The API_Moq_HttpContext class is the one that implements the Mocking infrastructure

public class API_Moq_HttpContext
        public Mock<HttpContextBase> MockContext { get; set; }
        public Mock<HttpRequestBase> MockRequest { get; set; }
        public Mock<HttpResponseBase> MockResponse { get; set; }
        public Mock<HttpSessionStateBase> MockSession { get; set; }
        public Mock<HttpServerUtilityBase> MockServer { get; set; }
        public Mock<IPrincipal> MockUser { get; set; }
        public Mock<IIdentity> MockIdentity { get; set; }
        public HttpContextBase HttpContextBase  { get; set; }
        public HttpRequestBase HttpRequestBase  { get; set; }
        public HttpResponseBase HttpResponseBase  { get; set; }       
        public API_Moq_HttpContext()
        public API_Moq_HttpContext createBaseMocks()
            MockContext = new Mock<HttpContextBase>();
            MockRequest = new Mock<HttpRequestBase>();
            MockResponse = new Mock<HttpResponseBase>();
            MockSession = new Mock<HttpSessionStateBase>();
            MockServer = new Mock<HttpServerUtilityBase>();
            MockContext.Setup(ctx => ctx.Request).Returns(MockRequest.Object);
            MockContext.Setup(ctx => ctx.Response).Returns(MockResponse.Object);
            MockContext.Setup(ctx => ctx.Session).Returns(MockSession.Object);
            MockContext.Setup(ctx => ctx.Server).Returns(MockServer.Object);
             HttpContextBase = MockContext.Object;
             HttpRequestBase = MockRequest.Object;
             HttpResponseBase = MockResponse.Object;
             return this;
        public API_Moq_HttpContext setupNormalRequestValues()
            var MockUser = new Mock<IPrincipal>();
            var MockIdentity = new Mock<IIdentity>();       
            MockContext.Setup(context => context.User).Returns(MockUser.Object);
             MockUser.Setup(context => context.Identity).Returns(MockIdentity.Object);
             MockRequest.Setup(request =>request.InputStream).Returns(new MemoryStream());
             MockResponse.Setup(response =>response.OutputStream).Returns(new MemoryStream());
             return this;


At the moment it has a couple extension methods to help writing and reading data from the HttpRequest InputStream and HttpResponse OutputStream

    public static class API_Moq_HttpContext_ExtensionMethods
        public static HttpContextBase httpContext(this API_Moq_HttpContext moqHttpContext)
            return moqHttpContext.HttpContextBase;
        public static HttpContextBase request_Write(this HttpContextBase httpContextBase,string text)
            httpContextBase.stream_Write(httpContextBase.Request.InputStream, text);           
            return httpContextBase;
        public static string request_Read(this HttpContextBase httpContextBase)
            return httpContextBase.stream_Read(httpContextBase.Request.InputStream);
        public static HttpContextBase response_Write(this HttpContextBase httpContextBase,string text)
            httpContextBase.stream_Write(httpContextBase.Response.OutputStream, text);           
            return httpContextBase;
        public static string response_Read(this HttpContextBase httpContextBase)
            return httpContextBase.stream_Read(httpContextBase.Response.OutputStream);                       
        public static HttpContextBase stream_Write(this HttpContextBase httpContextBase, Stream inputStream, string text)
            var streamWriter = new StreamWriter(inputStream);
            inputStream.Position = inputStream.property("Length").str().toInt();
            inputStream.Position = 0;            
            return httpContextBase;
        public static string stream_Read(this HttpContextBase httpContextBase, Stream inputStream)
            var originalPosition = inputStream.Position;
            var streamReader = new StreamReader(inputStream);
            var requestData = streamReader.ReadToEnd();   
            inputStream.Position = originalPosition;
            return requestData;

April 5, 2011 - Posted by | Moq


  1. […] the Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq) API, here is a unit test that uses it to test if a method used inside an HttpModule is doing the […]

    Pingback by Unit Test for HttpModule using Moq to wrap HttpRequest « O2Platform.com for Developers | April 10, 2011 | Reply

  2. […] Mocking HttpContext HttpRequest and HttpResponse for UnitTests (using Moq) […]

    Pingback by Script to fetch and present large number of Wordpress.com blog entries « O2Platform.com for Developers | April 16, 2011 | Reply

  3. inputStream.Position = inputStream.property(“Length”).str().toInt();

    Is this an error???????

    Comment by Elliot | February 28, 2012 | Reply

  4. And this:

    var httpContext = mockHttpContext.httpContext();


    Comment by Elliot | February 28, 2012 | Reply

    • That one is correct. That httpContent() method will return a HttpContextBase object, ie this:

      HttpContextBase httpContext = mockHttpContext.httpContext();

      I called it httpContext since the idea is that you should be using this HttpContextBase object instead of the native HttpContext object. The HttpContextBase is created via:

      HttpContextBase = MockContext.Object;

      where MockContext is

      MockContext = new Mock();

      Comment by Dinis Cruz | February 29, 2012 | Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: