5

I'd like to unit test some controller actions and ultimately test that validation attributes and action response filters are functioning properly. To do this sort of thing in ASP .NET MVC was easy with mvccontrib; however, with Web API, mocking the HttpContext seems to be quite a bit different.

How do I go about mocking HttpContext for a Web API controller so that I can test model binding and the like?

2 Answers 2

2

You shouldn't need HttpContext in a Web API. Everything you need should be in the HttpRequestMessage and its Properties collection.

Sign up to request clarification or add additional context in comments.

3 Comments

What about application settings in HttpContext.Current.Application?
@Scotty.NET Use request.Properties to store whatever state you need to store. If you need stuff global state in there, then create a message handler to store the state and add it to the properties collection on each request.
You have confirmed what I was thinking would be the case. Thanks for that.
0

Do not use HttpContext. Just Mock the service and the controller and go with somthing like this:

_serviceMock.Setup(s => s.YourFunction(params if needed)).Returns(return value).
var response = _controllerMock.YourFunction(parameter);
_serviceMock.VerifyAll();
var result = response.Result;
var value = result.Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.