Mocking HttpRequestBase.ServerVariables using Moq
Mocking is a very handy tool for unit testing code, especially when it comes to mocking the HttpContext
for web application code. However, it’s not as straight forward as you might think to mock the HttpRequestBase.ServerVariables
, however once you know what to do it really is pretty simple.
Here’s a code example, using moq, that shows how to create a mock HttpContextBase that contains a mock HttpRequestBase with a mock ServerVariables property:
public HttpContextBase CreateMockHttpContext()
{
var serverVaraibles = new NameValueCollection {
{ "SomeServerIPAddress", "127.0.0.1" },
{ "AnotherAppVariable", "Unit Test Value" }
};
var httpRequest = new Moq.Mock<HttpRequestBase>();
httpRequest.Setup(x => x.ServerVariables.Get(It.IsAny<string>()))
.Returns(string>(x => {
return serverVaraibles[x];
}));
var httpContext = (new Moq.Mock<HttpContextBase>());
httpContext.Setup(x => x.Request).Returns(httpRequest.Object);
}
Hopefully this points someone in the direction they are looking to be able to write more unit tests for code that contains dependencies on the HttpContext
.
Related Posts
-
C#: Console App that Accepts Command-Line Arguments
23 Apr 2024 -
C#: How to iterate over a dictionary?
20 Apr 2024 -
C#: What is the difference between 'string' and System.String?
16 Apr 2024