views:

243

answers:

4

How do I get an ASP.NET MVC controller properly initialized for an integration test?

My current problem is that when I try to access the User member of a controller I get:

System.NotImplementedException: The method or operation is not implemented.

What I want is what Ruby on Rails provides out of the box with the Functional Tests.

A: 

You'll need to fire up an instance of the webserver, whether it be IIS or the built-in Visual Studio one. The unit testing in Visual Studio doesn't initiate a instance of the site by default.

The Matt
How do I fire up IIS or Casini from a test?
J. Pablo Fernández
+1  A: 

To fire up Cassini from a unit test

 [TestMethod()]

 [HostType("ASP.NET")]

 [UrlToTest("http://localhost:25153/WebSite1")]

More information on MSDN

Kindness,

Dan

Daniel Elliott
+2  A: 

How about having a gander at this from Steve Sanderson - MVCIntegrationTestFramework

Looks pretty freakin cool!

HTHs,
Charles

Charlino
Sounds very close to what I want. Am I right in assuming that the demo project is the only downloadable thing it's offered? The framework is not offered anywhere else than in the demo, or so it seems.
J. Pablo Fernández
One problem that I see though is that it'll use whatever database is configured in web.config, that mean it'll normally use the dev database, instead of the test database I generate on the fly for the tests.
J. Pablo Fernández
You could couple it with something like this: http://www.hanselman.com/blog/ManagingMultipleConfigurationFileEnvironmentsWithPreBuildEvents.aspx ...?
Charlino
A: 

You have few choices:

  1. Mock HttpContextBase - there're plenty of articles on the subject
  2. Use injection - pass IUserContext to controller, and mock it in tests (in real app it will be something HttpUserContext)
  3. Use model binder: http://www.hanselman.com/blog/IPrincipalUserModelBinderInASPNETMVCForEasierTesting.aspx

And I'm sure there's more, for example, make your BaseController and fake GetUser() there as needed.

queen3
But I don't want to mock any of those, because I want to make sure my application works fine with the real context, the real session, etc.
J. Pablo Fernández
That is, this is not a unit test, it's an integration test.
J. Pablo Fernández
Sorry, missed that word. Then your choice is one of the options suggested here. MVCIntegrationTestFramework looks promising. This post seems to explain AppDomain technique a bit deeper: http://www.lostechies.com/blogs/chad_myers/archive/2008/06/24/hosting-an-entire-asp-net-mvc-request-for-testing-purposes.aspx.
queen3
Or just use WatiN/Selenium, but of course with PageObject technique to eliminate code duplication.
queen3