So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".
I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.
I'm using latest version of rhino mocks
The procedure for this seems to have changed slightly in MVC2 (I'm using RC1). Phil Haack's solution doesn't work for me if the action requires a specific method (
[HttpPost]
,[HttpGet]
). Spelunking around in Reflector, it looks like the method for verifying these attributes has changed. MVC now checksrequest.Headers
,request.Form
, andrequest.QueryString
for aX-HTTP-Method-Override
value.If you add mocks for these properties, it works:
Here is a sample unit test class using MsTest and Moq which mocks HttpRequest and HttpResponse objects. (.NET 4.0, ASP.NET MVC 3.0 )
Controller action get value from request and sets http header in response objects. Other http context objects could be mocked up in similar way
Here's a snippet from Jason's link. Its the same as Phil's method but uses rhino.
Note: mockHttpContext.Request is stubbed to return mockRequest before mockRequest's internals are stubbed out. I believe this order is required.
Or you can do this with Typemock Isolator with no need to send in a fake controller at all:
I find that long mocking procedure to be too much friction.
The best way we have found - using ASP.NET MVC on a real project - is to abstract the HttpContext to an IWebContext interface that simply passes through. Then you can mock the IWebContext with no pain.
Here is an example
i've finished with this spec
and the juice is here
enjoy