驭字广州话怎么读音:Dean Hume

来源:百度文库 编辑:九乡新闻网 时间:2024/10/06 01:59:22

Test your MVC routes with Moq

Tweet

Routing is a great feature that ships with MVC. The ASP.NET Routingmodule is responsible for mapping incoming browser requests toparticular MVC controller actions. One of the great things about routingin MVC is the ability to rewrite a URL and make it a lot more readable.This is also meant to be better for SEO, but I like that fact the URL'sare easy to type and easier to remember.

If you've had a look at an ASP.NET MVC application before you willnotice that it handles URL's differently to your standard ASP.NETWebforms. One of the things that I worry about when playing around withthe routing is messing up other routes. This is where unit testing comesin very handy.

A great way to test this would be to use a Mocking framework. I normally use Moq,but you could use any .Net based mocking framework. For this examplehowever, we will stick to Moq. If you haven't worked with Moq before,please take a look at these two other posts that I have written on them here and here.

Lets take a look at the default route that is included in our Global.asax file.

One of the advantages of using Moq in this instance, is thatit allows us to create a fake HttpContextBase and HttpRequestBase. Letsapply this and write a unit test to test this:

In the first section (Arrange), we are setting up the fake data thatthe HttpContextBase should return. Once that is done we tell it toreturn the route"~/Home/About".

We then get our RouteCollection to return the route data for that HttpContextBase that we have setup.

And finally, we are checking all the values that are returned to seeif they match the Controller, the action and any Id that was passed in.Let's try this same pattern for another route that is a little morecomplicated. We should be able to test for similar results.

In this instance, the route is slightly different. We are also going to add a bit of complexity by adding some parameters.

Again we are mocking an HttpContext and setting it up to return the route "~/Home/Product/Jeans/2".If this were in a controller and we were passing a model to the view,we would expect the view to return a product with an id of 2 - ie a pairof jeans.

Finally, we can test that the values passed in the URL - "~/Home/Product/Jeans/2" are getting sent and the routes are getting mapped correctly.

I hope this helps with any issues you may have had with testing yourroutes in MVC. It might also be a good idea to run a set of testsagainst your routes whenever you make any changes!

 

Date: