Posts tonen met het label WatiN. Alle posts tonen
Posts tonen met het label WatiN. Alle posts tonen

woensdag 16 februari 2011

Released WatiN 2.0 Final

Last week I have release WatiN 2.0 Final (2.0.50.1179). You can download the zip file from Sourceforge:

http://sourceforge.net/projects/watin/files/WatiN%202.x/2.0%20Final/WatiN-2.0.50.1179.zip/download

or install it using NuGet (need to have the Package Manager console for Visual Studio 2010 installed, get it at nuget.org). To add it to your project is as simple as:

PM> Install-Package WatiN

The release notes can be found on the new website http://watin.org (which is still in flux but getting there)

http://watin.org/documentation/release-2-0-50-11579/

Enjoy Testing with WatiN!

vrijdag 15 januari 2010

Browser.AttachTo<T> and IAttachTo

In WatiN RC1 the functionality to attach to a browser instance has had a complete redo. This had two reasons:

  1. Being able to attach to a browser in a browser agnostic way.
  2. Being able to return your custom browser type.

Download the example code here

From the old way to a browser agnostic way

If you don’t intend to run your tests with different browsers, you still need to make a small change in your code when upgrading to WatiN RC1.

image

needs to be changed into

image

which is the same as

image

and the same as

image

As you can see in the last example, you can pass in a type which should inherit WatiN.Core.Browser. The following example shows you how to utilize this method in situations where you get a browser instance injected into your test code. In the example the link that is clicked on will open up a new browser instance and we want to verify the text in this newly opened browser instance.

image

Thanks to this new AttachTo(type, findBy) method there is no knowledge at all of the used browser type inside my test code.

Returning a custom Browser type from AttachTo()

Many of us who use WatiN will probably use their own custom super duper version of WatiN.Core.IE. Providing new or different behavior then the default IE implementation does. See here for example  (and yes this part of the post was also a little bit sparked by their need to write their own AttachTo methods).

Here is my great MyIE class which overrides the ToString method and returns the Title and Url of the shown page (it’ll surf just as an example).

image

And now I want to be able write

image

When I run this piece of code, WatiN will throw this exception:

WatiN.Core.Exceptions.WatiNException: 
No AttachToHelper registered for type WatiN.Examples.Tests.MyIE.

That does sound like Ican register an AttachToHelper for a browser Type, doesn’t it. The Browser class provides a method RegisterAttachToHelper doing just that.

So we need to create our own AttachToMyIEHelper class. Since MyIE is inheriting IE, AttachToMyIEHelper will inherit AttachToIEHelper. And then it is just a matter of overriding the CreateBrowserInstance method, return a new instance of MyIE and we are done. Here is the implementation:

image

And this code shows you how to register the new AttachToMyIEHelper and use it in your tests.

image

Enjoy testing with WatiN.

Technorati Tags:

Combine WatiN and White to test Silverlight

Googling the web for stuff written about WatiN, I came across this very interesting article to combine forces between WatiN and White.

http://leobartnik.net/blog/2010/01/silverlight-uiautomation-testing-using.html

It also sparked this idea:

var  silverlightControl = browser.Control<SilverlightControl>(Find.ByFirst());

silverlightControl.Button(Find.ById(“someButton”)).Click;

Interesting.

Technorati Tags:

dinsdag 22 december 2009

Released WatiN 2.0 RC 1

A short shout out to announce the release of WatiN 2.0 Release Candidate 1.

Many fixes and new features since the last beta 1 release way back in March. I’m still compiling the list of changes so check back on this page later this week. But if you follow my blog you are well informed already. If you haven’t been using beta 1, start reading the release note of that release here.

And of course  you want to download the new release.

Enjoy testing with WatiN!

Technorati Tags:

vrijdag 11 december 2009

Wrapping complex logic in a Control

Update 18 December 2009: Added missing file to code download

WatiN is all about simplifying the way you can interact with a web browser and the elements on a page. Simple elements are just wrapped (like divs, links and alike) but for more complex elements WatiN offers you functionality which hides complex interactions with the browser. For instance TextField.TypeText will not only set the value of an input field but will also fire all the appropriate events, basically simulating a real user typing in text.

But what if you want to automate/model some action that involves complex logic and/or multiple elements. Yes indeed I am referring to all those ASP and third party controls out there. In this post I will show you how to create your own control which you can use as if it is an element on the page and natively supported by WatiN.

You can download the code for this post here (which also contains a build of WatiN 2.0 RC1)

The control to automate: JQuery-UI Datepicker

I’m going to show you how to create a basic control for the jQuery UI Datepicker. But that’s simple you might think, just use TypeText of the TextField class, the WatiN wrapper for input elements of type text. True, but then I need to think about formating the date correctly every time I automate a datepicker. And there might be other things I would like to check on the datepicker (see  jQuery-UI Datepicker for all the options that can be set and read on this widget). So I’m going to use the javascript API of the datepicker to automate the control.

imageimage

Wondering how to use this control in your test code?

image

Looks familiar (and simple) doesn’t it.

The implementation of DatePicker

To create the control I need a root WatiN.Core.Element subtype which will be the base/root Element for my DatePicker control. Since a html input of type text serves as the root element for the jQuery UI datepicker widget, it makes sense that DatePicker will use TextField as its root Element.

image

Since I decided I’m going to use the datepicker’s javascript API, the control needs to execute scripts inside the browser. Fortunately WatiN offers this functionality through the RunScript() and Eval() methods, both exposed by the DomContainer class. Control<T>, the base class for every control, exposes the property Element which returns the root Element of the control, in this case TextField. From there we can get to the DomContainer to execute javascript using Eval().

image

Next thing to do is to create the javascript to set the date using the API of the jQuery datepicker. This is what the script needs to look like to set the date to 10 December 2009 (indeed the month is 11, a javascript thingy):

window.jQuery(element).datepicker(‘setDate’, new Date(2009, 11, 10));

To make sure that the javascript references the correct html element in the DOM, I will make use of the new method  GetJavascriptElementReference(), available on every (subtype of) Element (in WatiN 2.0 RC1). And of course the Date should be created  correctly.

I’m also using window.jQuery() instead of window.$() to make sure this script will also work when $() is not a shortcut for the jQuery() function (but instead is used by some other javascript library like Prototype).

I will combine all this in the setter part of the Date property of the DatePicker control:

image

For the getter part there is one catch, transforming the returned javascript date in to a DateTime instance. Fortunately DateTime.Parse parses a UTC date format without any problem, so I let the javascript return the date in such a format.

image 

Now that we can set and get the date of the jQuery UI Datepicker widget we can start using it in our tests. And it offers a create place to add more functionality.

To conclude

I hope this post will help you start creating controls for your own or third party controls. There is much more that you can do so check out the download with this post to see:

  • How to restrict the use of this control to input elements which are a datepicker.
  • How to handle Date = null and reading a null date.
  • How to read options set on a datepicker widget instance.

There is also a WatiN-Contrib project started on Google code. So if you like to share your third party WatiN control library, let us know.

Enjoy testing with WatiN!

Technorati Tags:

zondag 6 december 2009

Using WatiN to parse and scrape HTML

Of course you can scrape web pages with WatiN so why this blog post you might ask. Well, with the out-of-the-box WatiN browser support you need to instantiate a browser to get the HTML for a page and scrape it. If you don’t need to interact with the page, like clicking on links, type in some text or rely on cookies for session state, you don’t need all the overhead (memory, start up time) of the browser.

This article will show you how you can use WatiN browserless by implementing a new browser: MsHtmlBrowser, using techniques described in this article.

For this code I use the current development code which will soon be released as WatiN 2.0 RC. You can download the code for this post here.

Load a url with HTMLDocumentClass

The trick to make this work is to make use of IPersistStreamInit and HTMLDocumentClass.

First lets get the definition of IPersistStreamInit in place:

image

And this is how we can combine it with the HTMLDocumentClass (don’t forget to add a reference to the assembly Microsoft.mshtml.dll distributed with WatiN):

image

Using multi browser support in WatiN 2.0

Knowing this we now need to give this code a place in the WatiN architecture. With the introduction of multi browser support in WatiN 2.0, the architecture of the WatiN API has been changed to allow adding new implementations for different browsers without having to change the WatiN.Core code. To create a new Browser implementation we need to create concrete implementations for the INative* interfaces specific for the browser we are adding. Since we are basing our new browser implementation on the same mshtml dll that Internet Explorer uses, we can reuse a lot of the IE specific native classes already available in the WatiN.Core.Native.InternetExplorer namespace.

But since we don’t want to use WatiN.Core.IE and need to use WatiN.Core.Browser to tap into the WatiN architecture, we need to create our own browser class. Lets call it MsHtmlBrowser (inheriting the abstract class Browser). This forces us to implement 2 abstract methods (WaitForComplete and Close) and 1 abstract property (NativeBrowser). Lets focus on implementing the NativeBrowser property.

Implementing MsHtmlNativeBrowser

NativeBrowser returns a type implementing INativeBrowser. So lets create a class MsHtmlNativeBrowser which implements INativeBrowser. This requires several methods and properties to be implemented. Many of these we can’t provide an implementation for since we aren’t wrapping a real browser. Two of these we need to focus on NavigateTo(url) and the property NativeDocument.

As you might guess, we can add our code (to load a page in an HtmlDocumentClass instance) to the NavigateTo method. After initialization of the object we wrap it into an IEDocument which will be returned by the NativeDocument property. Following the implementation. All the other methods do throw a NotImplementedException.

image

Back to implementing MshHtmlBrowser.

MsHtmlBrowser continued

Now that we have MsHtmlNativeBrowser, we can return an instance of this class in the NativeBrowser property of MsHtmlBrowser.

The implementation of the Close method is empty since we don’t have a real browser we need to close. You might consider disposing the instance of MsHtmlNativeBrowser here.

For the WaitForComplete method we can reuse functionality in the IEWaitForComplete class by passing in the IEDocument instance of the MsHtmlNativeBrowser.

This results in the following implementation:

image 

 

Using the new MsHtmlBrowser

image

Which concludes this example on creating a browserless Browser implementation.

Enjoy testing with WatiN!

Technorati Tags:

maandag 26 oktober 2009

WatiN and MbUnit, a nice combo

Just a shameless repost of a mail Jeff Brown did send to the WatiN mailinglists. Interesting stuff, go check it out!

ANN: New samples for using WatiN with MbUnit.

I just released Gallio / MbUnit v3.1 Update 1.

It's mainly a bug fix release but I also added some new samples
demonstrating one good way of using WatiN with MbUnit.

The sample introduces a new custom attribute called [Browser] with some
fancy behavior like:

* Capturing a screenshot if the test fails (or whenever you like).
* Embedding a video capture of the test run if the test fails (or whenever
you like).
* Running the same test repeatedly with different browsers.

The code is pretty easy to use so if you're already using MbUnit v3 and
WatiN then you should find it pretty easy to incorporate some of these
features from the samples into your own tests.

After installing Gallio v3.1 Update 1, look in %PROGRAMFILES%\Gallio\samples
for the WatiN samples and unzip them to a location of your choice.  You'll
need Visual Studio 2008 SP1 to run them out of the box.

Here's one of the sample tests to give you an idea of how this looks:


       /// <summary>
       /// Runs the same test repeatedly with different browsers.
       /// </summary>
       [Test]
       [Browser(BrowserType.IE)]
       [Browser(BrowserType.FireFox)]
       [Browser(BrowserType.Chrome)]
       public void MultipleBrowsers()
       {
           GoogleSearchPage.GoTo(Browser);
           Browser.Page<GoogleSearchPage>().Search("Fiddlesticks");
       }


Full announcement and download links:
http://blog.bits-in-motion.com/2009/10/announcing-gallio-and-mbunit-v31-upda
te.html


You can also see a sample video capture from a previous release here:
http://www.youtube.com/watch?v=rN0CmutflFs

Enjoy,
Jeff.

Technorati Tags:

vrijdag 26 juni 2009

Page class gets friends

In my previous blog post I explained how you can use the new Page class in your code. Having this class available did spark some new ideas in the community. And again Jeff Brown offered some hours of sleep to make your page classes even more terse by introducing the FindByAttribute. Another new attribute is the DescriptionAttribute.

FindByAttribute

The FindByAttribute can be used on Fields and Properties and gives you a declarative style of expressing how an element should be found. In the following example the GoogleSearchPage is revamped and makes use of the new FindByAttribute.

image

Note that I only changed the GoogleSearchPage class and didn't have to change the test. And yes indeed, no actual c# code is needed and it almost reads like a real sentence. If only we could get ride of the syntax overhead like the [()] public:

FindBy Name q TextField SearchCriteria

And there is more

Talking about readability, Daaron Dwyer suggested to add a DescriptionAttribute. This new attribute sets the (also new) Description property of an Element or Control instance. This description is set on the element when a page object gets instantiated. With the description you can give the element a meaningful name which will show up in the log WatiN can create (see the Logger class in WatiN). The description will also be used when ToString() is called on an Element or Control.

If you like to have a look at these brand new features then go and get the source from the SourceForce code repository. If you are a little less adventures today, just wait until the next WatiN 2.0 release.

woensdag 17 juni 2009

Introducing the Page class

When you create your first automated tests with WatiN you are happy with the results and how easy it is to create tests (at least that is what I keep hearing). Your happily copying and pasting code to find elements into new tests. While your test suite is growing rapidly, changes are made to the web pages and all of a sudden you are in a test code maintenance nightmare. You have created WET code (!= DRY). The solution: separate your test code in tests classes, page classes and control classes (more on controls in another post). So lets start mopping!

Richard Griffin, James Avery and Ayende Rahien all wrote about the problems they were having and the page model they developed. Bruce McLeod even posted the WatiN Jobsite Sample on CodePlex to show you his page model in action. Thanks to the work of Jeff Brown, WatiN 2.0 beta 1 now comes with its own page model. The basic idea of a page model is that each web page in the web site under test has a page class counterpart in the test suite. These page classes expose elements through properties and actions through methods. The result makes it much easier to create new tests and to maintain your test code when changes happen to your web site.In this post I’ll transform the Hello world example of web test automation, as shown on the WatiN homepage, into a test using such a page class.

First a new class needs to be created inheriting the WatiN.Core.Page class, lets call it GoogleSearchPage. This page class exposes properties for the searchcriteria field and the search button. After re-writing the “Hello world example” using the GoogleSearchPage class, the code looks like this (and of course you would put the GoogleSearchPage class in its own file/assembly in production code, but for this example I kept them together).

image

The Page<> method on the Browser class provides an easy way to instantiate page classes and it does inject the Browser Document into the page class. Because the GoogleSearchPage inherits the new WatiN.Core.Page class, it can access to Document property exposed by the Page class to find elements on the page.

Since the GoogleSearchPage has properties exposing the SearchCriteria textfield and the Search button, all logic to find these controls is held in one place and can be easily reused in other tests. Also notice how the test got much more readable compared to the example on the WatiN website.

Ok, so we have modeled the page with its elements, lets take it one step further. Most web pages offer users one or more actions they can perform on the page. Modeling these actions as methods on your page class would encapsulate even more logic into one place and thus making it easier to maintain when changes happen to the web page. So let me add the method SearchFor to the GoogleSearchPage. Also see how it improves the readability of the test, again.

image

At this point, when I would navigate to http://www.bing.com and use the GoogleSearchPage, nothing would alarm me that the current page can’t be automated with the GoogleSearchPage class. Instead an ElementNotFoundException would be throw when trying to find an input element with the name btnG (in the SearchCriteria property).

The new Page class offers you some ways to validate the current page before accessing elements on the page. The easiest way is to decorate a page class with the new PageAttribute. This attribute exposes a property UrlRegex which accepts a regular expression. This is used to match with the current browsers Url every time the Page.Document property is accessed. WatiN will check if the browser is still on the correct page and if not, throw a meaningful exception.

If the regular expressions are not your thing or you want to check against another aspect of your page (for instance the title), you can also override the Page.VerifyDocumentProperties method and implement your own check and not use the PageAttribute.

Wel that’s it about the new Page class in WatiN 2.0 beta 1. I hope it will help you to better structure your page model. Following our revamped Hello world example of web test automation.

image

Technorati Tags:

dinsdag 7 april 2009

WatiN How To screen cast

I have been thinking for a while about creating a How To screen casts series about WatiN. Last week I sat down and experimented a bit with Jing by TechSmith (the creators of CamtasiaStudio).

With Jing it really is very easy to get started with recording and not falling into the trap of creating the visually perfect video with Camtasia. Which, at the end, never gets done. I also like the 5 minute constraint that Jing enforces. This really makes you to focus on the core of things you want to example or show. And last but not least, they offer a 2 GB free storage on screencast.com to host your videos.

For this How To trial episode I used this blog about adding your own elements to WatiN. Let me know what you think about it? Do you like the length, the amount of information, should I do more like these and which topics would you like to be explained?

Watch the episode.

Technorati Tags:

Introducing the DialogHandlerHelper

Many questions on the watin-users mailinglist (and about WatiN in general) are about handling dialogs with WatiN. WatiN has build in support for handling many of Internet Explorers dailogs but it is hard to find out which DialogHandler is the right one for the job.

WatiN 2.0 beta 1 introduced the new DialogHandlerHelper class. DialogHandlerHelper can be used to investigate which DialogHandler can be used for a specific dialog. The following example shows you how to use the DialogHandlerHelper .

image

Lets walk through the example. First it creates an IE instance and navigates to a page. Then an instance of DialogHandlerHelper is created and registered with the DialogWatcher. A button is clicked which shows a dialog. The DialogHandlerHelper will now inspect the dialog and close it. Finally the CandidateDialogHandlers are written to the console window for you to inspect and create your final solution.

For this example that would be:

image

 

Just a thought

To make it even more simple, wouldn’t it be great if someone combined the following into a windows forms app:

  • http://www.codeproject.com/KB/dialog/FindWindow.aspx: To let the user point at the dialog that needs to be automated.
  • The code inside DialogHandlerHelper to inspect the chosen dialog and find candidate dailoghandlers.
  • And, when a Dialoghandler is available for the dialog, uses the the class documentation that comes with the dialoghandler to show you example code about using that specific dialoghandler.

Volunteers?

Technorati Tags:

dinsdag 31 maart 2009

Reusing an IE instance in VS test

I was going over the WatiN questions on stackoverflow. One of the questions involved reusing an IE instance over multiple tests. Since Visual Studio’s test runner creates a new Thread for each TestMethod in a TestClass you get a nasty InvalidComObjectException with the additional information "COM object that has been separated from its underlying RCW can not be used.".

Following the problem example as posted on stackoverflow. When running these tests, the first test “testOne” passes but the second test “testTwo” will throw the InvalidComObjectException.

image

Does this mean we can’t reuse an IE instance across multiple tests? Nope.

We can still instantiate IE in the method decorated with the ClassInitialize attribute but in each test case we need to attach to the running instance using IE.AttachToIE(constraint). To find the Internet Explorer instance we created, we can use the window handle to find the instance. Somewhat like a “good-old-pointer”. Add a little bit logic to cache the found IE instance and return this as long as the CurrentThread hasn’t changed and the helper class could look something like this:

image

To make use of this helper class, we create an instance of IEStaticInstanceHelper and assign it to a static field (as we did before with the IE instance). Next we assign an IE instance to the IE property. Now we can use this Internet Explorer instance in our test cases without bothering about different Threads.

For clarity sake I wrapped the call to the  ieStaticInstanceHelper.IE property in an instance property of the test class, called IE. And to make sure the IE instance gets closed after all tests have run I added a method decorated with the ClassCleanup attribute.

 

image

Off course you could create a base class which is used by all your test classes, but that's up to you.

You can download the code here.

Happy testing with WatiN and Visual Studio test runner!

Technorati Tags:

maandag 30 maart 2009

Released WatiN 2.0 beta 1

I’m very happy to announce the release of WatiN 2.0 beta 1!

It has been a long ride from the first CTP release to this beta release. This has mainly to do with the beta having a completely different architecture from the previous CTP releases. With the CTP releases we used interface like ITextField etc. to provide support for multiple browsers. This resulted basically in creating a complete new set of about 50 classes for each additional browser we wanted to support. With this release we have managed to reduce this amount to 6 classes for each additional browser.

Another big change is made to the test suite. All the tests that came with WatiN 1.3 and were run against Internet Explorer, making sure every feature worked with IE6 and IE7, are now run against FireFox 2 and 3 and IE8 as well. This ensures that all features have the same behavior across all these browsers.

We are not there yet, that’s why it is still a beta release. We will continue working on WatiN 2.0 to fix the list of known issues and to incorporate community feedback. We intend to do a release at the end of every month, working towards a final release in June or July.

In the coming days I will blog some more about the new features. For now you can read the release notes at http://watin.sourceforge.net/releasenotes-2-0-10-x.html and download the release here.

Happy testing with WatiN!

Technorati Tags:

donderdag 26 maart 2009

Custom elements and controls in WatiN 2.0 beta

Update 3/31/2009: You can download the example code for this blog post here.

Still working on the beta release of WatiN 2.0 (will ship in the next few days), but I felt the need to blog about a new feature in the 2.0 beta. In previous posts I showed you how you could extend WatiN with your own controls:

In the upcoming beta WatiN will offer you these new features:

  1. Add support for native html elements not provided by WatiN.
  2. Add support for your (custom) web controls.

Which make the previous posts obsolete.

Add your own native html element

WatiN doesn’t provide support for all html elements defined by the W3C standards. For instance there is no out-of-the-box support for li tagged elements. But starting with WatiN 2.0 beta 1 you can “add” support for linked lists yourself.

First lets show you how you could make use of your own ListItem element.

ListItem list = browser.ElementOfType<ListItem >(Find.ById(“theElementId”));

(And yes, this syntax also works with the out-of-the-box elements like TextField etc..)

Now we know how we could use a none native ListItem element in our (test) code, lets create this ListItem class.

  1. First create a new class called ListItem and make it inherit WatiN.Core.Element.
  2. Add the ElementTagAttribute to your class to tell WatiN which tagName(s) your element class can handle. Incase of ListItem: [ElementTag(“li”)]
  3. Add whatever properties and methods are needed to make this element work for you.
  4. The last thing you need to do is register ListItem with WatiN’s ElementFactory before you can use it in your (test) code:

ElementFactory.RegisterElementType(typeof(ListItem ));

That’s it, you’ve added a new (almost native) element to WatiN. You could make it look even more native by extending the IElementContainer  interface with some extension methods which do wrap the calls to ElementOfType<ListItem >(…) and make it look like:

ListItem list = browser.ListItem (Find.ById(“theElementId”));

Add support for your (custom) web controls

I’ll tell you about that one in my next post… back to releasing the beta :-)

Technorati Tags:

woensdag 11 februari 2009

Released WatiN 2.0 CTP3

I'm happy to announce the third CTP release of WatiN 2.0, offering support for both Internet Explorer and FireFox.

Changes in this release

  • Implemented support on Mozilla.Frame to get access to elements inside the document of a Frame.
  • Implemented support on Mozilla.Frame to get access to elements inside the document of an IFrame.
  • Implemented Eval on Mozilla.Document (= FireFox and Frame) and added to the IFrame interface

Fixed bugs

  • Form.Submit didn't wait for a possible postback and page load.

Enjoy testing with WatiN!

Tags van Technorati:

dinsdag 9 december 2008

WatiN roadmap

Today I received a question on the mailing list about the status of WatiN 2.0. I thought I publish my response here as well.

No release date(s) yet, but I can report about the progress and speculate about a roadmap:

  • Currently the development code (a continuation of the 1.3 code base) is refactored to add support for testing with different browsers (IE, FireFox for now). I estimate I'm at 60% of the changes that need to be done to get the basic stuff to work.
  • Next is the integration of the firefox specific code from the 2.0 CTP version into the development code. I estimate that I will go for a first integration around the end of this month.

So my current guesstimate is that a beta or final release of 2.0 will be earliest at the end of q1 2009.

In the meantime Edward Wilde will update the current 2.0 CTP version to add support for FireFox 3.x. We haven't spoken about a release date be hopefully this refresh will be available early next year.

I will also release WatiN 1.3.1 in December with some important bug fixes.

So nothing final yet but I hope this gives you (all) a feel of what we are aiming for.

WatiN Find.ByDefault explained

My next post will be Part III of Supporting custom elements with WatiN. I got so excited about the possibilities that I started working on a wrapper for the Ra-Ajax controls as a show case. It is becoming very COOL and its fun to create as well. But as I said in my next post I'll show you more.

This post is all about a new feature of WatiN 1.3 which might not be that discoverable so I felt it needed some promotion.

Find.ByDefault

When you want to automate some action against an element on a web page, WatiN offers you different types of elements (TextField, Button, etc) to find an element. Each of these offer overloads accepting something to find the element by. For example, if you want to find a TextField by its id ("firstName_Id" in this example) you would typically have this code:

var firstNameField = ie.TextField("firstName_Id");

Which is the same as:

var firstNameField = ie.TextField(Find.ByDefault("firstName_Id"));

And with the default Settings applied, it is the same as:

var firstNameField = ie.TextField(Find.ById("firstName_Id"));

In this post I'll show you how you can change the implementation and behavior of Find.ByDefault() by creating your own default factory class and assigning it to Settings.DefaultFinderFactory .

Make Find.ByName the default

If your site makes heavy use of the name attribute on elements (instead of ids) and you use these to find the elements in your tests, you would typically write code like:

var firstNameField = ie.TextField(Find.ByName("firstName_Name"));

Lets make Find.ByName() the default so your code will look like this:

var firstNameField = ie.TextField("firstName_Name");

To make this work we need to create a new class which implements IFindByDefaultFactory. In the implementation of the ByDefault(string) method we can simply return Find.ByName(value). This is the implementation of the class:

public class FindByNameFactory : IFindByDefaultFactory
{
public BaseConstraint ByDefault(string value)
{
  return Find.ByName(value);
}
    public BaseConstraint ByDefault(Regex value)
{
  return Find.ByName(value);
}
}

The last thing we need to do is register this new factory class and Find.ByName will be the new default:

Settings.FindByDefaultFactory = new FindByNameFactory();

Handle ASP ids with

Another very useful way we could leverage this new feature is dealing with ASP.Net ids. When you automate a website which is build with ASP.Net webforms you probably have to deal with very long ids. By default ASP.Net creates unique ids by concatenating all of the ids of the container controls a control is in. For instance if a TextBox to enter a first name is placed within a tab control container and this is placed in a placeholder, the resulting id could be something like "plc_Main$tab_Details$txt_FirstName". With WatiN you have several ways to find this TextField by id.

Option 1: Using the full Id
The simplest option to find the control is to use the full id. Example:

ie.TextField("plc_Main$tab_Details$txt_FirstName").TypeText("Jeroen");

There are two disadvantages to this approach:
- It relies heavily on the ids of the controls the ASP:TextBox control is placed in. If you remove/rename or add another container to the stack, the TextField won't be found cause the id is changed.
- The longer the id gets the less readable this line of code becomes. Although you can (should in my opinion) abstract the way you find your controls by using a Page model, this still is massy.

Option 2: Using a regular expression
The second option is to find the control by using the overload on TextField which accepts a regular expression. In the following example we create a Regex which matches TextFields ending (hence the $ sign) with "txt_FirstName" :

ie.TextField(new Regex("txt_FirstName$")).TypeText("Jeroen");

Option 3: Make WatiN handle ASP ids by itself

public class FindByAspIdFactory : IFindByDefaultFactory
{
public BaseConstraint ByDefault(string value)
{
  return Find.ById(new Regex(value + "$"));
}
    public BaseConstraint ByDefault(Regex value)
{
  return Find.ById(value);
}
}

Register this new factory class:

Settings.FindByDefaultFactory = new FindByAspIdFactory();

And you can find controls with ASP ids like:

ie.TextField("txt_FirstName").TypeText("Jeroen");

Using (magic) prefixes

If you don't like to always use a regular expression, like we did in the previous example, you could implement something like the Incisif automation framework offers. They choose to put a prefix in front of the ASP id. So only if the specific prefix (a:) is in the id a lookup with a Regex will be done to find the element. Example:

ie.TextField("a:txt_FirstName").TypeText

and the Factory implementation:

public class FindByAspIdFactory : IFindByDefaultFactory
{

public BaseConstraint ByDefault(string value)
{
  if (value.StartsWith("a:")
  {
   Regex regex = new Regex(string.format("(.*\${0}$)|(.*_{0}$)", value));
   return Find.ById(regex);
  }
  return Find.ById(value);
} 

public BaseConstraint ByDefault(Regex value)
{
  return Find.ById(value);
}
}

Other possible uses

Put the attribute you want to match with in front of the value

ie.TextField("id:txt_FirstName").TypeText
ie.TextField("name:txt_FirstName").TypeText

A ruby like notation to express a regular expression (starting and ending with a forward slash) instead of having new Regex() all over your code:

ie.TextField("/txt_FirstName$/").TypeText

And I'm sure you can come up with many more possible uses.

Enjoy!

woensdag 12 november 2008

Supporting custom elements with WatiN, Part II

12 Nov 2008: Updated section about creating an extension method.

In part I of this series I explained why you should create wrappers and how you could create a basic wrapper for your custom or third party controls. In this post I will show you

  • how to make use of the deferred find execution
  • how to use extension methods to make it all look integrated with WatiN

What is Deferred Find Execution

Deferred Find Execution in WatiN means that the search for an element in the current web page is done the first time you get a property value, set a property value or call a method on that element. An example:

using(IE ie = new IE())
{
TextField name = ie.TextField("name");

ie.GoTo(new Uri(Util.HtmlTestBaseURI, "EnterYourName.htm"));
name.TypeText("Jeroen");
}

The first line will open a new Internet Explorer instance showing you an empty page (about:blank). Next we set the name variable to point to an input element of type text with the id 'name'. If WatiN did an immediate lookup it would throw an ElementNotFound exception cause these elements aren't on the page shown in the browser. But WatiN doesn't throw an exception, it actually returns an instance of TextField for which the find isn't executed yet. Then the browser navigates to a page with this name element on it. When calling TypeText on the TextField instance, WatiN will search for (and find) the input element with id 'name' before executing the TypeText action. So finding of the name element is deferred until the code actually needs a reference to that element.

WatiN heavily relies on this behavior so it seems like a good idea to play with the rules.

Implementing deferred find execution

To make this work for the DateTimeElement an element finder class needs to be passed to the base class of DateTimeElement. Lets replace the current constructor, which accepts a Table instance, with one that calls the base constructor accepting an INativeElementFinder instance. For readability I created a private method CreateElementFinder which does the actual creation of the INativeElementFinder instance. The base constructor also needs a DomContainer instance which can be provided by our IE instance in our test code. Here is the reviced code for DateTimeElement:

public class DateTimeElement : Table
{
public DateTimeElement(DomContainer domContainer, string id) :
base(domContainer, CreateElementFinder(domContainer, id)) { }

public void TypeDateTime(DateTime value)
{
TextField(new Regex("^date$")).TypeText(value.ToString("dd-MM-yyyy"));
TextField(new Regex("^time$")).TypeText(value.ToString("hh:mm:ss"));
}

private static INativeElementFinder CreateElementFinder(DomContainer domContainer,
string id)
{
return domContainer.NativeBrowser.CreateElementFinder(ElementTags,
Find.ById(id),
domContainer);
}
}

And here is how the code in our test looks like:

DateTimeElement element = new DateTimeElement(ie, "datetime2");
element.TypeDateTime(new DateTime(2008, 11, 1, 12, 00, 00));

All in all a small code change for a big change in behavior.

Introducing CustomElementFinderHelper

In the above code I choose to create the ElementFinder instance inside the DateTimeElement class. I did this because my focus was on introducing deferred find execution (always make small steps). But if we are going to create more wrappers for our custom or third party controls, this CreateElementFinder method seems to be needed in all of them. So lets do some refactoring and move this method into a new class which will be passed into the constructor of DateTimeElement. Here is the new class CustomElementFinderHelper:

public class CustomElementFinderHelper
{
private readonly DomContainer _domContainer;
private readonly BaseConstraint _constraint;

public CustomElementFinderHelper(DomContainer domContainer,
BaseConstraint constraint)
{
_domContainer = domContainer;
_constraint = constraint;
}

public DomContainer DomContainer
{
get { return _domContainer; }
}

public INativeElementFinder CreateElementFinder(ArrayList supportedTags)
{
return _domContainer.NativeBrowser.CreateElementFinder(supportedTags,
_constraint,
_domContainer);
}
}

And this is our cleaned up DateTimeElement code:

public class DateTimeElement : Table
{
public DateTimeElement(CustomElementFinderHelper helper) :
base(helper.DomContainer, helper.CreateElementFinder(ElementTags)) { }

public void TypeDateTime(DateTime value)
{
TextField(new Regex("^date$")).TypeText(value.ToString("dd-MM-yyyy"));
TextField(new Regex("^time$")).TypeText(value.ToString("hh:mm:ss"));
}
}

And to top things of, the extension method

Our last refactoring has turned our testing code into an unreadable mess:

CustomElementFinderHelper helper = new CustomElementFinderHelper(ie, Find.ById
("datetime2"));
DateTimeElement element = new DateTimeElement(helper);
element.TypeDateTime(new DateTime(2008, 11, 1, 12, 00, 00));

The intention is completely lost and there is stuff we need to do over and over again if we use a DateTimeElement in our test automation. Again refactoring to a method will help, but wouldn't it be nice if we could use the same syntax in our tests as we use to find for instance a TextField. So we need to extend the IE class in some way.

One option would be to create a new sub class of the IE class, add a new method to find the DateTimeElement and use the sub class in all our tests.

A new and simpeler solution to get the same intellisense support and readable code in your tests, is the use of an extension method. We do have several options for our extension. We could use the IE class to extend. But a better candidate would be the DomContainer (inheritted by IE) so that this extension method is also available on the HtmlDialog class (for html popup dialogs). With our current implementation of CustomElementFinderHelper extending DomContainer seems to be the logical choice. So lets create a static DateTimeElementExtensions class with an extension method on DomContainer:

public static DateTimeElement DateTimeElement(this DomContainer domContainer,
string id)
{
CustomElementFinderHelper helper = new CustomElementFinderHelper(domContainer,
Find.ById(id));
return new DateTimeElement(helper);
}

And thanks to the magic of extension methods the code in our test now looks like:

ie.DateTimeElement("datetime2").TypeDateTime(new DateTime(2008, 11, 1, 12, 00, 00));

This refactoring cleans up the code big time and makes it look like DateTimeElement is part of the WatiN API itself. Ain't that sweat.... :-)

If your still using C# 2.0, first go to your manager and (again) explain why you need to move to C#3.0 (and it's a breeze!). If the answer (again) is NO than remove the this keyword from the method signature and you can call it like this:

DateTimeElementExtensions.DateTimeElement(ie, "datetime2").TypeDateTime(new
DateTime(2008, 11, 1, 12, 00,00));

Almost there

And now you want to access a DateTimeElement as a child from a Frame, Div or Table element..... That is a no go with the current solution.

In part III I will show you how we can fix this by making some changes to the CustomElementFinderHelper and again the magic of extension methods. But this time on one of WatiN's interfaces.

vrijdag 7 november 2008

Supporting custom elements with WatiN, part I

When using WatiN it is easy to automate simple actions on standard elements in the browser. But when you try to automate (complex) controls of control vendors like Telerik, Infragistics or even your own custom controls, things get to start ugly quickly. Wouldn't it be nice if we could automate these controls in the same way we do automate a TextField ?

In this blog post and the next one, I while show you how.

The html code to automate

Lets start small and simple. The following HTML snippet is created by a (fictitious) custom date time control. For one of our (again fictitious) tests we need to set the values of the date and time input elements.

<table id="datetime2">
    <tr>
        <td>
            <input type="hidden" id="original_date" value="01-01-2007" />
            <input type="text" id="date" value="01-01-2007" />
        </td>
        <td>
            <input type="hidden" id="original_time" value="10:00:00" />
            <input type="text" id="time" value="10:00:00" />
        </td>
    </tr>
</table>

As you can see the html for this date time control contains two input fields, one for the date and one for the time. There are also two hidden input elements containing the original values of the input fields.

The simple way

To automate setting the date and time the following code will do the job nicely.

IE ie = new IE("http://www.examples.watin.net/datetime.html");

ie.Table("datetime2").TextField(new Regex("^date$")).TypeText("01-11-2008");
ie.Table("datetime2").TextField(new Regex("^time$")).TypeText("12:00:00");

So what's wrong with this code you might wonder. It basically comes down to being code and logic that isn't reusable. To name two issues:

  • To get the correct TextField for the date or time, you need to remember (or find out the hard way) the correct regular expression. Otherwise you might end up setting the value of the hidden input element which will give you a nice exception (and then you remember... and I can tell).
  • The formatting of the date and time needs to be in this specific format for the control to work.

We could refactor this into a method, but still. WatiN offers you all kinds of objects that wrap html elements so it feels more natural for this date time control to be wrapped as well.

Basic wrapping

So lets create a wrapper. I will use Table as the base for our new element class since Table seems to be the container element for the control.

public class DateTimeElement : Table
{
    public DateTimeElement(Table table) : base(table) { }

    public void TypeDateTime(DateTime value)
    {
        TextField(new Regex("^date$")).TypeText(value.ToString("dd-MM-yyyy"));
        TextField(new Regex("^time$")).TypeText(value.ToString("hh:mm:ss"));
    }
}

We can use this new DateTimeElement class in our tests like this:

DateTimeElement element = new DateTimeElement(ie.Table("datetime2"));
element.TypeDateTime(new DateTime(2008, 11, 1, 12, 00, 00));

In my opinion the readability and intention of this code is way better then our first approach. And it also encapsulate the knowledge of the regular expression and the specific formatting of the date and time.

So are we happy now. Not completely. I think the syntax of creating the new DateTimeElement can be improved cause it feels weird to pass in a table element instance into the constructor. Another, not visible, drawback of passing in an element is that it doesn't use WatiN's deferred execution to find the table element on the page. In more complicated wrappers this might lead to unexpected behavior. For now I will spare you the details.

Stay tuned

In part II I will show you how you can get deferred find execution by providing a small helper class and making some changes to the DateTimeElement constructor.

To top things off I will use extension methods (C# 3.0 only) to give you this end result in you test code:

ie.DateTimeElement("datetime2").TypeDateTime(new DateTime(2008, 11, 1, 12, 00, 00));

Stay tuned....

Tags van Technorati:

woensdag 23 april 2008

WebUnitAsp 2.0

If you like the way NUnitAsp handled things this might be one for you. WebUnitAsp (http://dotnet.org.za/colin/archive/2008/04/22/webunitasp-2-an-experiment-in-unit-testing-asp-net.aspx) is a wrapper around the WatiN API and gives you the look and feel of using NUnitAsp. This version of WebUnitAsp is based on the WatiN 2.0 CTP.

Tags van Technorati: