I am writing a unit test and the controller method is throwing an exception because HttpContext / ControllerContext is null. I don't need to assert anything from the HttpContext, just need it to be not NULL. I have done research and I believe Moq is the answer. But all the samples that I have seen haven't helped me a lot. I don't need to do anything fancy, just to mock the httpcontext. Point me in the right direction!
HttpContextMock is an implementation of AspNetCore. Http. HttpContext that stores a Mock<HttpContext> instance and works as a proxy for the real Mock. The HttpContextMock constructor initializes a Mock for Request, Response, Header and etc to work as a proxy as well.
Advanced: Mocking in Unit TestMocking is used in unit tests to replace the return value of a class method or function. This may seem counterintuitive since unit tests are supposed to test the class method or function, but we are replacing all those processing and setting a predefined output.
Got these two functions from here in a class;
public static class HttpContextFactory
{
public static void SetFakeAuthenticatedControllerContext(this Controller controller)
{
var httpContext = FakeAuthenticatedHttpContext();
ControllerContext context =
new ControllerContext(
new RequestContext(httpContext,
new RouteData()), controller);
controller.ControllerContext = context;
}
private static HttpContextBase FakeAuthenticatedHttpContext()
{
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>();
var user = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
context.Setup(ctx => ctx.User).Returns(user.Object);
user.Setup(ctx => ctx.Identity).Returns(identity.Object);
identity.Setup(id => id.IsAuthenticated).Returns(true);
identity.Setup(id => id.Name).Returns("a.ali174");
return context.Object;
}
}
From the unit test I called them as such;
HttpContextFactory.SetFakeAuthenticatedControllerContext(controller);
Make sure you have Moq installed in your tests project:
Install-Package Moq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With