Mocking HttpContext for unit tests

In this post, I will share the problem that I stumbled upon while writing unit tests for the code block that pulls values off the HttpContext. And yes, I started out writing unit tests finally, after several years of .NET programming.


I needed to unit test a module that pulls a value (in my case, it was the IP address of a client machine) off the HttpContext.


The problem was that when I tried to unit test this code block, I could not mock HttpContext directly since it is sealed. Also, I kept getting null reference exception as the current context did not exist when called from the unit test method. So, my unit test threw exception and did not run and kept on turning RED. 😦

Continue reading