MS MVC: Testing Routes
In Scott’s post about routing he showed how you can easily test routes. One cool thing about 3.5 asp.net extension framework is the introduction of new interfaces for IHttpContext, IHttpRequest, IHttpResponse, and some other. This makes testing with mocks so much easier. Here I will show you some tests I wrote to validate the routing rules we created for simply restful routing in the ms mvc framework.
What Are We Testing?
When testing we want to stick with one assertion per test. So for this example we are only testing that the rules we wrote set the proper action. You can view the rules we will be testing in my previous post.
Create The Test Fixture
using System.Collections.Specialized; using System.Web; using System.Web.Mvc; using MVCContrib.SimplyRestful; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using Rhino.Mocks; namespace MVCContrib.Specs.SimplyRestfulSpecs { [TestFixture] public class SimplyRestfulRouteMatchTests { } }
Add The First Test
[Test]
public void GetRouteData_WithAControllerAndIdUsingAHttpGetRequest_SetsTheShowAction()
{
}
Our test name is using pattern Method_Context_Result. So the method under test is GetRouteData. The context of the test is With a controller and id using a an http get request sets the show action. Now lets fill in the test.
[Test]
public void GetRouteData_WithAControllerAndIdUsingAHttpGetRequest_SetsTheShowAction()
{
IHttpContext httpContext;
RouteCollection routeCollection = new RouteCollection();
SimplyRestfulRouteHandler.InitializeRoutes(routeCollection);
RouteData routeData = routeCollection.GetRouteData(httpContext);
Assert.That(routeData.Values["action"], Is.EqualTo("show").IgnoreCase);
}
Above we wrote our assertion. We want to call the GetRouteData method on a routeCollection and we want to assert that the parameter named “action” is equal to show. At this point the test will fail with a nre on httpContext. httpContext needs to be an instance of IHttpContext, so how do we get an instance of an interface. Simple, we mock it. We will setup the mock context with just enough information for the RouteCollection to do its job. This could be considered a stub and not a mock since we are simply using Rhino.Mocks to setup results.
[Test]
public void GetRouteData_WithAControllerAndIdUsingAHttpGetRequest_SetsTheShowAction()
{
MockRepository mocks = new MockRepository();
IHttpContext httpContext = mocks.DynamicMock<IHttpContext>();
IHttpRequest httpRequest = mocks.DynamicMock<IHttpRequest>();
RouteCollection routeCollection = new RouteCollection();
SimplyRestfulRouteHandler.InitializeRoutes(routeCollection);
using(mocks.Record())
{
SetupResult.For(httpContext.Request)
.Return(httpRequest);
SetupResult.For(httpRequest.AppRelativeCurrentExecutionFilePath)
.Return("~/products/123");
SetupResult.For(httpRequest.HttpMethod)
.Return("GET");
}
using(mocks.Playback())
{
RouteData routeData = routeCollection.GetRouteData(httpContext);
Assert.That(routeData.Values["action"], Is.EqualTo("show").IgnoreCase);
}
}
So what just happened? First we created a MockRepository which is the core engine of Rhino.Mocks. This could probably get moved to a [SetUp] method. Next we create two Dynamic Mocks. One for the context and one for the request. We make them dynamic mocks because they are not under test. We do not care what gets called on these interfaces or how it gets called. We just care that if certain properties are called they return a specific values emulating what a real http request would look like. Next we have the mocks.Record phase. This is used to demarcate expectations versus assertions.
What to note is that the RouteCollection uses the AppRelativeCurrentExecutionFilePath property which expects a return string like “~/something/something/something.aspx” we are telling it to return “~/products/123″ products is our controller and 123 should be our id of the route. Next we setup a result for the Httpmethod property, remember our Route had validation on the special name Method which maps to a call on HttpMethod.
Finally we run our test and make the assertions. We enter playback mode, execute the GetRouteData method, which is our method under test, pass in the mocked context and assert that the returned routedata has a parameter named “action” = “show”
So once you add a couple more tests for different routes you will see a way to factor some common code out. I created a helper method to setup my context.
private void SetupContext(string url, string httpMethod, string formMethod) { SetupResult.For(httpContext.Request).Return(httpRequest); SetupResult.For(httpRequest.AppRelativeCurrentExecutionFilePath).Return(url); SetupResult.For(httpRequest.HttpMethod).Return(httpMethod); if(!string.IsNullOrEmpty(formMethod)) { NameValueCollection form = new NameValueCollection(); form.Add("_method", formMethod); SetupResult.For(httpRequest.Form).Return(form); } }
Then my tests simply look like this.
[Test]
public void GetRouteData_WithAControllerAndIdUsingFormMethodPut_UsesSimplyRestfulRouteHandler()
{
using (mocks.Record())
{
SetupContext("~/controller/123", "POST", "PUT");
}
using (mocks.Playback())
{
RouteData routeData = routeCollection.GetRouteData(httpContext);
Assert.That(routeData.Route.RouteHandler, Is.EqualTo(typeof(SimplyRestfulRouteHandler)));
}
}
The best part about writing tests for this stuff is you no longer have to fire up a browser and test by hand. You get instant verification that runs quick.
If you are wondering how I figured out what to mock and setup results for it was a quick perusal of System.Web.Extensions in reflector. Having to open reflector to figure out what to mock is a code smell for me. You really shouldn’t be mocking things you don’t own or control but this is a nice quick integration test that can save you tons of time down the road. Just don’t be surprised if after an update you get some errors because MS changed the implementation of RouteCollection.GetRouteData, another great reason for using a ContextSetup method.
[...] you for making my routes so easy to test. I now have confidence that everything is working without having to fire up IIS and a browser to [...]
So….. where is toilet? Hehe))) Joke, relax
)
Thank you
bye bye
Srsly though, where IS toilet?
Even if all people of your family see one on a daily basis, relationship continues to vital. It is generally the simplest way to enhance the bond among the loved ones and also you could make your romance to each other tougher. Really it is wonderful to behave exterior but once the conditions is certainly not superior or maybe it really is raining out of doors, you can consider a variety of indoors online games and exercises which will genuinely make every person feel happy. This is an excellent option that one could remember to consider. Right here are some of the video game titles or routines you can do inside your own home.Hide and go seek has become the most widely used online games ever before performed which will be done indoors. An individual must be an In .it” who definitely are responsible of trying to find other members of the family who are covering. The first that’ll be discovered with no holdingPerachieving your home basic should function as the subsequent Inchesit.Half inch But should you be imagine that this is simply not an excellent method, you possibly can consider charade which happens to be an additional interior video game. With this online game, ultimately, there needs to be two clubs. There’ll be part that can act on the idea of that is published on a piece of paper whilst the fellow members are usually in-control over questioning the word. The c’s with items should be stated because the victorious one.In addition to hide and seek and charade, a large variety of card and board games will also be one of several great choices that you may consider. Card games include Menagerie, Outdated Cleaning service, In business, Stone, Slapjack and much more. For games, you possibly can choose Scrabble, Mentally stimulating games, Monopoly, Spouse and children Feud and Pieces. Since you also have plenty of choices to see, you simply need to select one that you feel is actually entertaining.Alternatively, if you find that participating in the game titles that have been stated earlier are not adequate, you may choose other suggestions which the majority of the family members have likes and dislikes in. As an example, job to cookPercook as a way the kids, then you can certainly turn this into task so as to attachment with your loved ones. You may designate each and every associate to do a certain portion of the cooking/cooking food course of action making sure that everybody will delight in. Make certain that everyone actually gets to attend this kind of hobby. As soon as your meals are cooked properly or maybe the cake is baked, you’ll be able to try to eat it with each other because of the family members. Everyone will surely be content to have the fruit of the labour. Apart from preparing food/cooking, you may also take into consideration other sorts of pursuits like piece of art, bouncing, performing, reading, watching motion pictures and plenty of a lot more.These are simply quite simple ways to connect with the family however, these are truly effective. It is not necessary for yourself devote a ton of money as these straightforward elements can unquestionably take joy to anyone particularly household is finish. It isn’t really actually critical that these items should be done each day. Once a week or even a rare occasions a month will do.
Even when all members of ones own see the other person daily, binding is essential. It is basically the ultimate way to bolster the link one of many loved ones and perhaps design your romance together tougher. It’s really great to do something out-of-doors but when the conditions is certainly not superior or maybe it can be pouring outside, you can consider different types of in house games and actions which will truly make absolutely everyone feel happy. This is a great substitute that you may factor in. The following are the video games or even the exercises you can apply indoors.Hide and seek is probably the most widely used games ever before experienced and this will surely be performed in your own home. An individual really needs to be an InchesitIn that happen to be responsible of in search of other members of the family who will be concealing. Website that will be located without the need of touchingOrhitting your home base will are the subsequent Init.Half inch But for anyone who is feel that this may not be a great option, you possibly can consider charade that’s another interior video game. With this video game, ultimately, the converter should have two clubs. There will be part that could act out the term that is published on a piece of paper although the fellow members come in-charge of questioning the phrase. The group most abundant in factors will likely then be proclaimed for the reason that success.Apart from hide and seek and charade, a large variety of unit card and games will also be one of many perfect selections you can check into. Card games incorporate Menagerie, Ancient House maid, Rolling, Jewel, Slapjack and many others. For board games, you’ll be able to decide on Scrabble, Chess, Monopoly, Relatives Feud and Checkers. As you have plenty of choices to observe, less costly choose one which you think that is really enjoyment.In contrast, if you think playing the games that have been already stated will never be sufficiently good, it is possible to opt for alternative activities which a lot of the relatives have hobbies and interests in. As an example, if you value to cookAndfarrenheit if you want your kids, then you can certainly get this exercise as a way to connect with the family. You are able to determine every new member to perform a certain section of the baking/baking method to make sure that all people will relish. Guarantee that all people extends to get involved in this kind of action. Just as soon as food is grilled and the dessert is prepared, you may feed on it together together with the family members. Anyone will definitely be pleased to have the berries of these toil. Besides bakingOrpreparing your receipee, it’s also possible to take into account some other activities like artwork, bouncing, singing, looking at, watching shows and lots of much more.Mentioned quite solutions for rapport with the fam however, these are actually effective. You do not have available for you shell out big money as these uncomplicated items can undoubtedly carry pleasure to everyone specifically family members are finish. It isn’t actually needed that this stuff carried out each day. Once per week or simply a few times monthly will do.
Although all participants of ones own see the other each day, connection continues to be essential. This really is generally the easiest way to reinforce the call one of the members of the family and also make your romance to one another more robust. It is definitely wonderful to do something outside the house but should the weather conditions isn’t that excellent or maybe it is seeing exterior, you can think about different kinds of household video game titles and activities that could truly make everybody feel good. This is an excellent different that one could take into account. The following are the video game titles or the things to do that you can do inside your own home.Hide and go seek is amongst the most popular video games ever before experienced this really can be exercised indoors. Somebody ought to be an In .itInches who’ll be accountable of looking for other loved ones who’re trying to hide. The first that is to be found with out holdingOrreaching your house starting will likely then function as future “it.Inch But should you be think that this is simply not an amazing option, you possibly can take a look at charade that is a different interior video game. During this game, if possible, there ought to be two competitors. It will have an affiliate that could rebel the term that is certainly prepared on a piece of paper although the fellow members have been around in-handle of estimating the term. The c’s most abundant in items are able to be reported because success.Besides hide and seek and charade, a lot of avenues of greeting card and games are also one of the best decisions that you may consider. Cards consist of Menagerie, Outdated Maid, Coming, Jewel, Slapjack and much more. For board games, you are able to opt for Scrabble, Chess, Monopoly, Family members Feud and Pieces. Since you also have a lot of options to check out, you need to simply decide on the brains behind you believe really is exciting.In contrast, if you feel that enjoying the games that had been already mentioned won’t be sufficiently good, you are able to decide on other considerations which the majority of the family have likes and dislikes in. For instance, if you love to prepareVersusprepare in order your son or daughter, you’ll be able to makes pastime so as to attachment with the fam. It is possible to determine each one associate to do a specific perhaps the the bakingAndpreparing method to ensure all people will like. Ensure that everyone reaches engage in this kind of pastime. And when foodis grilled and the meal is cooked, then you could try to eat it collectively with all the close relatives. Absolutely everyone will truly be pleased to have the fruit in their job. Besides preparing food/preparing, additionally you can contemplate various other activities like art work, belly dancing, performing, looking at, observing films and several more.Mentioned incredibly solutions for bond with the family nevertheless these are very powerful. There is no need in your case shell out some huge cash simply because uncomplicated issues can definitely take contentment to absolutely everyone particularly folks are entire. It may not be seriously critical that these items should be carried out everyday. Once every seven days or possibly a few times per 30 days are going to do.