Friday 12 December 2008

ASP.NET and AJAX unit testing with Watin

I stumbled across a great .NET library for unit testing our websites. This was listed alongside a question that I answered about "must-have" .NET libraries on stackoverflow.

The Watin tool (pronounced "What-In") is a .NET library which allows you to issue simple commands for navigting around your web site and more importantly supports the Microsoft AJAX control toolkit (as well as other Ajax implementations).
I used the following code to login to our travel product, navigate to the hotels page and search for a hotels with a town via an ASP.NET autocompleter control.

IE ie = new IE("http://localhost/mytavelproduct");
//login

ie.TextField(Find.ByName("txtUsername")).TypeText("username");
ie.TextField(Find.ByName("txtPassword")).TypeText("password");
ie.Button(Find.ByName("cmdLogin")).Click();

//goto the hotel search pageie.Link(Find.ByUrl("http://localhost/mytavelproduct/Hotel/HotelSearch.aspx")).Click();

//gradually populate the ajax autocompleter field in the town field

TextField field = ie.TextField(Find.ByName("ctl00$cphM$ucHotelLocationSection$txtTown"));
field.TypeText("lo");
Thread.Sleep(1000);

field.TypeText("nd");
Thread.Sleep(1000);

field.TypeText("on");
Thread.Sleep(1000);
//the autocomplete dropdown should have appeared at this stage...

However, in order for the above code to work with the Ajax autocomplete dropdown control, I had to jump through a few hoops.

The first issue is detailed as follows on blogspot http://lazyloading.blogspot.com/2008/06/testing-aspnet-ajax-autocomplete.html

Adding an attribute to the ajax control on page load, performed some "Runtime event reanimation" which allowed the TypeText methods of Watin to be captured by the ajax control.Without this the mocked key presses are ignored.

The second issue was related to javascript that we had on the page. The Watin code appears to loose focus, or blur the control between methods. Unfortunately the onblur event is used by us to clear the text value if nothing has been selected from the ajax autocompleter. By removing this javascript code from the control (with a view to moving it to the page Submit button?) the ajax dropdown is now displayed during the Thread.Sleep periods.

Having completed this and by browsing various blogs for the answer, I also found something that will generated the above code for you!!
http://watintestrecord.sourceforge.net/

This is not perfect (as the ajax stuff requires a bit of hand crafting) but this will take the leg work out of 90% of the coding.

Finally I have found a community out there building frameworks and further examples on how to use Watin.



This has been a long time coming. The Microsoft Web tests have simply not delivered, this is going to make life much easier

Cheers - Jon.

No comments: