I want to confirm that my "HomeController" class is being selected by the route I've created. So I have a test like this:
[TestMethod]
[UrlToTest("http://localhost:14478/home")]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("$(SolutionDir)\\MvcBuildApp")]
public void MyTest()
{
System.Diagnostics.Debugger.Break();
RouteCollection routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
MvcApplication.RegisterGlobalFilters(GlobalFilters.Filters);
//This fetches DefaultControllerFactory (for now, anyway...)
var factory = ControllerBuilder.Current.GetControllerFactory();
//mock a context...
var httpContext = CreateHttpContext("http://localhost:14478/home", "GET");
RouteData route = routes.GetRouteData(httpContext);
var ctrlInstance = factory.CreateController(new RequestContext(httpContext, route), (string)route.Values["controller"]);
//ASSERT the instance is of type "HomeController"
//...
}
It fails, saying that 'http://localhost:14478/home' completed successfully without running the test.
I noticed that in the VS output window, there is also this message No connection could be made because the target machine actively refused it 127.0.0.1:14478
. I figured Cassini must not be active. So I chose to launch the site being tested (ctrl+F5) before launching the unit test. It then changed the VS output to this:
WebTestAdapter.ConnectToHostAdapter: unexpected exception occured. Microsoft.VisualStudio.TestTools.HostAdapters.AbortTestExecutionException: Error in the application. at Microsoft.VisualStudio.TestTools.HostAdapters.WebTestAdapter.ConnectToHostAdapter()
To try to resolve this, I've followed the advice of these articles:
...but I still get the error no matter what I do. Suggestions?
UPDATE/CLARIFICATION
This question is not about testing MVC routes. The purpose of this question is to discover how to make ASP.NET MVC properly initialized to allow more "in depth" automated testing. I have chosen a "route testing" scenario, against the DefaultControllerFactory, merely as an example. In this example, the DefaultControllerFactory does not behave properly unless ASP.NET MVC is properly initialized.
This is a common requirement when testing MVC applications, and lucky you, there is a framework that will simplify your life when testing MVC controllers:
The tools is:
http://mvccontrib.codeplex.com/
And as an example you can create tests with just one line:
"~/".ShouldMapTo<HomeController>(controller => controller.Index());
As a reference:
http://geekswithblogs.net/thomasweller/archive/2009/11/02/unit-testing-asp.net-mvc-routes.aspx
http://www.arrangeactassert.com/how-to-unit-test-asp-net-mvc-controllers/
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