Tuesday, April 19, 2016

Mocking HttpContext in Unit Tests

One of the banes of writing Unit Tests is dealing with HttpContext which does not have an interface which can be easily Mocked like most other custom classes.

Fortunately, though, Microsoft has created a base class called HttpContextBase!

In my particular case, I needed to figure out how to mock HttpContext to use it in Unit Testing HttpCookie creation and retrieval.  I followed this article for guidance on just how to accomplish this task: http://blog.paulhadfield.net/2010/09/mocking-httpcookiecollection-in.html

Mock<HttpContextBase> HttpContextMock = new Mock<HttpContextBase>();
Mock<HttpRequestBase> RequestMock = new Mock<HttpRequestBase>();
Mock<HttpResponseBase> ResponseMock = new Mock<HttpResponseBase>();

HttpContextMock.Setup(x => x.Request).Returns(RequestMock.Object);
HttpContextMock.Setup(x => x.Response).Returns(ResponseMock.Object);
ResponseMock.Setup(r => r.Cookies).Returns(new HttpCookieCollection());

Using this Mock Setup code, I could now Unit Test my code which was dependent on HttpContext as well as the Request and Response objects for my HttpCookies!!

No comments:

Post a Comment