Working surgery for Watin.Net. All examples were created within Visual Studio 2008 set up for C# language. My aim is to show simple complete examples of working code mainly focused around google's website. By doing this will allow you the user to apply these examples to an actual website for themselves. If you are new to WatiN I suggest you follow the posts in order.

Wednesday, 11 March 2009

Post Five - Use Built in Variables

So now let's refactor the code to make it easier to read and maintain in the future. Were going to make use of our Element_ID class we prepared earlier. This will allow us to store ID's\names of elements within our code. For example the search text box weve used on Google's search page has a name of 'q' (I must admit not a very interesting or descriptive name) but none the less if we wish to use this textbox we must reference it by 'q'. Now let's say a few month's down the line we have written a hundred methods using the said textbox! And then Google in their wisdom change the name to 'x'! All our tests will break and we will have to track down all references to 'q' in all of our test to remedy the situation. But there is a better way. We store our 'q' reference in our Element_ID class so now all 100 test reference the same source for the name of 'q'. Now if Google do change the name to 'x' we only have one place to update and all our test will carry on working. So add the following 3 lines to the Element_ID class as shown below:

namespace WatinTestGround
class Element_ID
//Google Search
public const string GOOGLE_URL = "";
public const string SEARCH_TEXTBOX_ID = "q";
public const string SEARCH_BUTTON_ID = "btnG";

Update the 'GoogleSearch' method within the 'WorkingExamples' class to use the 'Element_ID' class as shown below:

public static void GoogleSearch()
//Line 1
IBrowser browser = BrowserFactory.Create(BrowserType.InternetExplorer);
//Line 2. Find the search text field and type Watin in it
//Line 3
ITextField searchText = browser.TextField(Element_ID.SEARCH_TEXTBOX_ID);
//Line 4
searchText.Value = "Watin";
//Line 5
IButton searchButton = browser.Button(Element_ID.SEARCH_BUTTON_ID);
//Line 6
//Line 7

You'll notice line 2, 3 & 5 now reference the 'Element_ID' class to obtain the ID's\Names we used to hard code within our methods.

No comments:

Post a Comment