mahesh sharma
mahesh sharma

Reputation: 1018

Mock HttpContext in web api using MOQ

I am trying to mock HttpContext for web api controller and using moq and did not get any relevant post regarding web api controller after googling so please help me.

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>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);
            context.Setup(c => c.Session).Returns(session.Object);
            context.Setup(c => c.Server).Returns(server.Object);


            return context.Object;

that way works for MVC but not in web api because we can pass HttpContextBase to ControllerContext in MVC but not in Web API.

Upvotes: 0

Views: 1330

Answers (1)

Luke
Luke

Reputation: 74

How do we feel about this?

public interface IHttpContext
{
    string Url { get; }
}

public class HttpContextProvider : IHttpContext
{
    public string Url => HttpContext.Current.Request.Url.ToString();
}

public class MockedHttpContextProvider : IHttpContext
{
    public string Url => "https://google.com";
}

I agree you shouldn't pass HttpContext deep into your application, but if you are refactoring old code and it's already been passed a long way down the tree, I find the below is a great way to write unit tests for your new code and not have to touch other peoples stuff!

Upvotes: 1

Related Questions