June 2008 - Posts
The Checkboxes method allows access to all the checkboxes on the web page. It is primarily used to find a checkbox when you are not able to access it by normal means, such as ID or Name.
The following test looks for a checkbox that follows a specific text label, and then tests changing its value.
Example of Usage
''' <summary> ''' Test behavior of checkboxes. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/main.html" ''' </remarks> <Test()> _ Public Sub TestCheckboxes() Using ie As IE = New IE(currentURL) Dim aCheckboxValue As Boolean = False Dim aCheckboxFound As Boolean = False Dim aCheckboxID As String = "" If ie.CheckBoxes.Length > 0 Then For Each CheckBoxFound As CheckBox In ie.CheckBoxes If Not IsNothing(CheckBoxFound.TextBefore) Then If CheckBoxFound.TextBefore.IndexOf("label before") > 0 Then aCheckboxFound = True aCheckboxID = CheckBoxFound.Id Exit For End If End If Next End If Assert.IsTrue(aCheckboxFound, "Checkbox preceded by text was not found.") aCheckboxValue = ie.CheckBox(aCheckboxID).Checked ie.CheckBox(Find.ById(New Regex(aCheckboxID))).Checked = Not aCheckboxValue Assert.AreNotEqual(aCheckboxValue, ie.CheckBox(Find.ById(New Regex(aCheckboxID))).Checked, "Checkbox did not change value.") ie.CheckBox(aCheckboxID).Checked = aCheckboxValue Assert.AreEqual(aCheckboxValue, ie.CheckBox(Find.ById(New Regex(aCheckboxID))).Checked, "Checkbox did not reset to original value.") End Using End Sub
Once the checkbox is found a few CPU cycles are saved by exiting the FOR loop, instead of just letting it go through to the end of the group. Then the ID of the found control is used to toggle the checked state of the checkbox.
Note: It was not necessary to determine if aCheckboxID contained a value before using it in the later portion of the test. This is because the Assert statement acts as a pseudo IF statement. If a checkbox was not found, and hence the aCheckboxID set, then the test would have stopped at that point, so there is no need to check for NULL status or other such checks.
Contents: Table of Contents Previous Page: WatiN API Reference - CheckBox Next Page: WatiN API Reference - ClearCache
The Checkbox method allows access to checkboxes on the web page, as you might expect. As with most controls that WatiN exposes, most of the properties are read only, such as text, tag name, etc.
The primary purpose of the method is to allow WatiN to examine the current value or to check or uncheck the value of a checkbox.
Example of Usage
''' <summary>
''' Test behavior of checkboxes.
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/main.html"
''' CheckboxOne is a Private Const = "Checkbox1"
''' </remarks>
<Test()> _
Public Sub TestCheckbox()
Using ie As IE = New IE(currentURL)
Dim aCheckboxValue As Boolean = False
aCheckboxValue = ie.CheckBox(Find.ById(New Regex(CheckboxOne))).Checked
ie.CheckBox(Find.ById(New Regex(CheckboxOne))).Checked = Not aCheckboxValue
Assert.AreNotEqual(aCheckboxValue, ie.CheckBox(Find.ById(New Regex(CheckboxOne))).Checked, "Checkbox did not change value.")
ie.CheckBox(Find.ById(New Regex(CheckboxOne))).Checked = aCheckboxValue
Assert.AreEqual(aCheckboxValue, ie.CheckBox(Find.ById(New Regex(CheckboxOne))).Checked, "Checkbox did not reset to original value.")
End Using
End Sub
This test merely saves the current state of the checkbox being tested, and then changes the value to show it can, finally restoring it to its original state.
It is generally considered good testing practice to return the web page or the database, if changes are made there, to its original state after a test, to ensure that the test can be run over and over with the expected results not corrupted by prior tests.
Contents: Table of Contents Previous Page: WatiN API Reference - CaptureWebPageToFile Next Page: WatiN API Reference - CheckBoxes
This is a very useful method for documentation and reviewing test results. Its purpose is to save a screen shot of the web page in its current state as an image file for later review. The type of image file saved is based on the file extension passed in the parameter. Currently file formats supported are: BMP, GIF, JPG, PNG, TIF. WatiN depends on the image encoders built into Windows, so if a particular encoder is missing, it will save the file in another image format.
The title bar and address bar are not included in the screen capture, just the browser window. Using this method liberally throughout your tests, it is easy to spot when things start to go wrong in a test with more than a few lines. Some developers like to capture a screen shot before every assert to assist in determining the failure when one occurs. This may be overkill, but when running more than a hundred tests, it is reassuring to know that the state of the screens are all being preserved for later review in case one fails.
Example of Usage
The following test is a reuse of part of the test created for ActiveElement, with the addition of the screen capture.
''' <summary> ''' Determine if the input textbox is initially the ActiveElement ''' and capture a screen shot. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/Default.aspx" ''' MessageTextBox is a Private Const = "MessageTextBox" ''' </remarks> <Test()> _ Public Sub TestActiveElementInitialFocus() Dim aStringValue As String = "" Using ie As IE = New IE(currentURL) If Not ie.ActiveElement.Id Is Nothing Then aStringValue = ie.ActiveElement.Id.ToString End If ie.CaptureWebPageToFile("C:\Doug\Default\TestActiveElementInitialFocus.jpg") Assert.IsTrue(aStringValue.Contains(MessageTextBox), "The initial focus should have been the textbox but instead was [" & aStringValue & "].") End Using End Sub
As shown in this test, it is a good idea to capture a screen shot before the assert is called, because if the assert fails, it is too late to do so.
A standard that some developers follow is to provide a folder for each test class (in this case the Default.aspx page is being tested) and then name the pictures after the test method with sequential numbers used to capture multiple images in the same test if there are several actions being tested.
Contents: Table of Contents Previous Page: WatiN API Reference - Buttons Next Page: WatiN API Reference - CheckBox
This method exposes a collection of all of the buttons on the current page in the current IE instance.
Once a button is located, it has its own set of properties which can be examined in addition to just being clicked. WatiN treats the button as a read only object so it is not possible to change the button text or other properties during the test.
Example of Usage
The following example will look at various aspects of the button collection:
''' <summary>
''' Examine the button collection for the page.
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/TestEvents.html"
''' </remarks>
<Test()> _
Public Sub ButtonsTest()
Dim aButtonCount As Integer = 0
Dim aButton As Button
Dim IsFound As Boolean = False
Using ie As IE = New IE(currentURL)
aButtonCount = ie.Buttons.Length
Assert.IsTrue(aButtonCount > 0, "There were no buttons on the page.")
Assert.IsTrue(ie.Buttons.Exists(Find.ById("confirmdialogid")), "Did not find by ID.")
Assert.IsTrue(ie.Buttons.Exists(Find.ByValue("Show alert dialog")), "Did not find by text value.")
aButton = ie.Buttons(0)
Assert.IsTrue(aButton.Text = "Button without id", "Button did not match text")
aButton = ie.Button(Find.ByText("Show alert dialog"))
Try
If aButton.Text = "Show alert dialog" Then
IsFound = True
End If
Catch ex As Exception
IsFound = False
End Try
Assert.IsFalse(IsFound, "Button found by text when not expected to.")
For Each aButton In ie.Buttons
If aButton.Text = "Show alert dialog" Then
IsFound = True
End If
Next
Assert.IsTrue(IsFound, "The show button was not found in the collection.")
End Using
End Sub
This method first gets a count of how many buttons are on the page and checks that some are in fact there. Then the test proceeds to see if several buttons exist by using several of the available find by options.
Finally, this test selects one of the buttons from the list and examines its properties.
Since buttons can be found directly from the IE instance without having to examine the button collection, this method is primarily useful when you know a button is there, but cannot quite get to it through normal means. The test demonstrates this with the “Show alert dialog” button. For some reason, WatiN refuses to find it by its text property even though the text is clearly visible on the screen and if you examine the properties of the button, the text is the expected value. By examining the collection one button at a time and it is found correctly.
Note: Putting the Try…Catch around the test for the button text property was necessary because the button did not actually exist at that time. The button is not Nothing, it just is not able to provide its values. This Try…Catch methodology saves the test from crashing but slows it down considerably. Once a situation like this is discovered, delete the slow part of the test entirely if there is another method such as shown here by examining the button collection.
Contents: Table of Contents Previous Page: WatiN API Reference - Button Next Page: WatiN API Reference - CaptureWebPageToFile
One of the most used methods available from the IE instance. A button on the screen can be examined or clicked with this method. Using WatiN to click a button fires its clicked event, as well as any javascript that may be attached to the button events, just as if a user had clicked the button with the mouse.
Once a button is located, it has its own set of properties which can be examined in addition to just being clicked. WatiN treats the button as a read only object so it is not possible to change the button text or other properties during the test.
Example of Usage
''' <summary>
''' Ensure that clicking the OK Button
''' adds text of the OKButton to the textbox.
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/Default.aspx"
''' OKButton is a Private Const = "OKButton"
''' MessageTextBox is a Private Const = "MessageTextBox"
''' </remarks>
<Test()> _
Public Sub TestButtons()
Using ie As IE = New IE(currentURL) 'Method ONE - Fully specify find criteria
ie.Button(Find.ById(New Regex(OKButton))).Click()
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("OK"), "TestButtons did not find OK in the textbox after OK button clicked.")
ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test"
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.")
'Method TWO - Implied Find.ByID
ie.Button(New Regex(OKButton)).Click()
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("OK"), "TestButtons did not find OK in the textbox after OK button clicked.")
ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test"
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.")
ie.Button(New Regex("OK")).Click()
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("OK"), "TestButtons did not find OK in the textbox after OK button clicked.")
ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test"
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.")
'Method THREE - Assign to object then exercise object
Dim aButton As Button
aButton = ie.Button(New Regex(OKButton))
aButton.Click()
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("OK"), "TestButtons did not find OK in the textbox after OK button clicked.")
ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test"
Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.")
End Using
End Sub
This example uses various methods of identifying or using a button object with WatiN. Method One uses the full specification of the button with the complete Find statement while the second method takes advantage of the implied Find, which makes the statement shorter. The implied find examines each of the Find By options until one of them is successful or all are exhausted. This can make the implied form slower to use if the ID property is not the one used for the Find.
Method Three adds the step of creating an object, then processing the method on the object. This method has the advantage that you can easily do other things with the object, such as examine the text caption or colors, but has the disadvantages of the overhead of object creation and destruction.
Contents: Table of Contents Previous Page: WatiN API Reference - BringToFront Next Page: WatiN API Reference - Buttons
This method causes the selected browser to become the top most window on the screen. This is useful if you want to see what is going on during the test and other windows are obscuring the browser.
Example of Usage
''' <summary>
''' Test if the browser will become top app on demand.
''' </summary>
''' <remarks>
''' Set AutoClose false on both browsers.
''' Should end with Live.com in browser on top.
''' </remarks>
<Test()> _
Public Sub BringToFrontTest()
Using ie As IE = New IE("http://www.live.com/")
ie.AutoClose = False
Using ie2 As IE = New IE("http://www.google.com/")
ie2.AutoClose = False
Assert.IsTrue(ie.Url = "http://www.live.com/", "Browser 1 not at URL.")
Assert.IsTrue(ie2.Url = "http://www.google.com/", "Browser 2 not at URL.")
ie.BringToFront()
End Using
End Using
End Sub
In this test, two browsers are opened and then the first is made to come to the front to be visible. Both browsers have their AutoClose property set False so the action can be viewed at the end of the test and both will have to be closed manually.
Contents: Table of Contents Previous Page: WatiN API Reference - Back Next Page: WatiN API Reference - Button
This method navigates the browser instance back one URL in the history queue, just like the back button on Internet Explorer or another browser application.
Warning: If you call this method before any navigation occurs in the browser or when all history has been exhausted and there is no URL to go back to, you will get the COM exception HRESULT E_FAIL.
Example of Usage
''' <summary> ''' Test if the browser back action will return the instance to its prior URL. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/Default.aspx" ''' Browser gets instantiated at Default, then navigates ''' to Live.com and is sent back to Default. ''' </remarks> <Test()> _ Public Sub BackTest() Using ie As IE = New IE(currentURL) Try ie.Back() Assert.IsTrue(False, "Should not get here. ie.Back did not trigger error when empty.") Catch ex As Exception ie.GoTo(currentURL) End Try ie.GoTo("http://www.live.com/") Using ie2 As IE = ie.AttachToIE(Find.ByTitle("Live")) Assert.IsTrue(ie2.Title.IndexOf("Search") >= 0, "Did not find other browser.") ie2.Back() Assert.IsTrue(ie2.Url = currentURL, "Did not process BACK action.") Try ie2.Back() Assert.IsTrue(False, "Should not get here. ie2.Back did not trigger error when empty.") Catch ex As Exception ie2.GoTo(currentURL) End Try End Using End Using End Sub
In this test the browser is successfully navigated back when history is available. Errors caused by no history being available are trapped and the browser returned to a valid URL.
Contents: Table of Contents Previous Page: WatiN API Reference - AutoClose Next Page: WatiN API Reference - BringToFront
This method sets a flag to indicate if the IE instance should close itself after the last reference to it is destroyed. The default is True, which is why the browser closes at the end of each test. If you want to keep the browser open after a test, for instance to take a look at something before you close it, set this flag to False. Generally, this is only done temporarily for one test because it quickly becomes tiring to have to manually close each browser window. Also, with the screen shot functionality built into WatiN, you can always look at the picture later if you want to know what was on the screen before it closed.
Examples of Usage
''' <summary>
''' Just test that the page opens.
''' </summary>
''' <remarks>
''' Look for >Home in the breadcrumb area.
''' </remarks>
<Test()> _
Public Sub InitTest()
Using ie As New IE(currentURL)
WatiNHelper.CaptureScreenShot(ie, PicturePath, "InitTest.jpg")
Assert.IsTrue(ie.ContainsText(">Home"), "Default Screen did not initialize properly.")
ie.AutoClose = False
End Using
End Sub
This is a simple test to open a page and determine if it did open. By setting AutoClose to False, you can examine the page prior to closing the browser yourself. Normally, WatiN would have closed the browser when the End Using was processed.
Contents: Table of Contents Previous Page: WatiN API Reference - AttachToIE Next Page: WatiN API Reference - Back
This method is used to attach an Internet Explorer instance from WatiN to an already active browser. This can be a “normal” Internet Explorer that the user has open, or can be another instance of the WatiN browser. This allows you to open a browser, complete some activities, and then have WatiN automate the remainder of the actions desired.
Note: At the end of the test, all browsers which have the same criteria as the instance used to attach will be closed. For example, if for some reason, you had five browsers open to Live Search and attached to one with WatiN using AttachtoIE, then all five would be closed by WatiN at the end of the test.
To find an instance of Internet Explorer to attach to, you can use the Title, the URL or the Window Handle.
Examples of Usage
The following example will open one browser (ie) and navigate to Live Search, then open another instance (ie2) attaching to the first instance and controlling it.
''' <summary> ''' Test if the browser will attach to an already open instance of IE. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/Default.aspx" ''' </remarks> <Test()> _ Public Sub AttachToIETest() Using ie As IE = New IE(currentURL) ie.GoTo("http://www.live.com/") Using ie2 As IE = ie.AttachToIE(Find.ByTitle("Live")) Assert.IsTrue(ie2.Title.IndexOf("Search") >= 0, "Did not find other browser.") ie2.Back() Assert.IsTrue(ie2.Url = currentURL, "Did not process BACK action.") End Using End Using
End Sub
Once the second instance is attached, it is used to navigate back in the history of the original browser to prove that it has controlled that browser, since the second instance has no history of its own.
Contents: Table of Contents Previous Page: WatiN API Reference - Area Next Page: WatiN API Reference - AutoClose