Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an ASP.NET MVC project with attribute routing be tested?

I've spent days trying to mock, stub and fake my way to a testable application. I usually don't test controller actions, but test all my other classes and patterns instead.

The wall I hit was with the new attribute routing feature. While I can use the routing classes to register my rules etc. I get this error when MapMvcAttributeRoutes is called.

This method cannot be called during the application's pre-start initialization phase

This is discussed here.

MapMvcAttributeRoutes: This method cannot be called during the application's pre-start initialization phase

To be honest, I can't understand the answer(s). Not the code, but its fragmented into versions, links to other bugs, GitHub etc.

I'm a bit lost as to the bottom line answer:

As of 23rd October, 2014. Is it possible to register all routes under test conditions, what version of MVC do I need and which classes/methods do I call to do it?

At present, my classes using UrlHelper are screwing up because needed routes are missing. I am injecting subclasses to bypass the issue, but I don't think its unreasonable to fake the runtime MVC environment and have my app run without lots of DI acrobatics.

It would be nice if these was a simple helper in the framework itself that could take a JSON object describing a raw HTTP request and have the Controller, HttpContext, ControllerContext etc. etc. all created properly as if it were a real request off the wire.

Thanks,

Luke

like image 259
Luke Puplett Avatar asked Sep 23 '14 16:09

Luke Puplett


2 Answers

Good question, and I think that the answer is that little or no thought was given to testing routes in the design of this part of the framework. There may be ways to test routes, but they will be indirect, undocumented and prone to break when a new version of MVC ships.

I have a blog post here on my experiences on the topic. I also suggest that you also campaign for better testability in ASP vNext in the public issue tracker.

like image 85
Anthony Avatar answered Nov 02 '22 08:11

Anthony


During a daily stand-up, a colleague mentioned he was integration testing via an in-memory web server. Intrigued, he showed me how and I was amazed, learnt something :-)

You can new-up an HttpServer instance and have it read your config and then invoke the server instance. I have not tried it, but I see no reason why this wouldn't enumerate your routes and code needing proper config will all work.

This SO question is related and may help in how to set this up:

How does the In-Memory HttpServer know which WebAPI project to host?

like image 41
Luke Puplett Avatar answered Nov 02 '22 08:11

Luke Puplett