This method is used to make visible the collection of DIV tags on a web page. DIV elements contain a host of properties to help manipulate the information therein.
Example of Usage
This example utilizes the main.html page that is distributed with WatiN to highlight some of the methods available with the DIV class.
''' <summary>
''' Test behavior of DIVs
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/main.html"
''' </remarks>
<Test()> _
Public Sub TestDivs()
Dim aDIV As Div
Dim aBoolean As Boolean = False
Dim aString As String = ""
Using ie As IE = New IE(currentURL)
For Each aDIV In ie.Divs
If aDIV.Text.Contains("Contains text in DIV") Then
aBoolean = True
Assert.IsTrue(aDIV.Tables.Length > 0, "DIV did not contain any tables.")
Exit For 'Found DIV in question, no need to look at the rest of them.
End If
Next
Assert.IsTrue(aBoolean, "Div did not contain expected text.")
End Using
End Sub
This test shows the most common use of the DIVS method, which is finding a DIV that does not have a known ID. Each DIV tag on the page is examined to match some known aspect (normally text) to locate the correct DIV, and then the DIV itself can expose the remainder of its properties for testing.
Contents: Table of Contents Previous Page: WatiN API Reference - Div Next Page: working on it
This method is used to make visible elements contained within a DIV tag on a web page. It contains a host of properties to help manipulate the information therein.
Example of Usage
This example utilizes the main.html page that is distributed with WatiN to highlight some of the methods available with the DIV class.
''' <summary>
''' Test behavior of DIV
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/main.html"
''' </remarks>
<Test()> _
Public Sub TestDiv()
Dim aDIV As Div
Dim aBoolean As Boolean = False
Using ie As IE = New IE(currentURL)
aDIV = ie.Div(Find.ById("divid"))
Assert.IsTrue(aDIV.Text.Contains("Contains text in DIV"), "Div did not contain expected text.")
Assert.IsTrue(aDIV.Tables.Length > 0, "Div did not contain a table.")
Assert.IsTrue(aDIV.Tables(0).TableRows.Length > 0, "Div table had no rows.")
Assert.IsTrue(aDIV.Tables(0).TableRows.Length = 2, "Div table did not have 2 rows.")
aString = aDIV.Tables(0).TableRows(0).TableCells(0).Text
Assert.IsTrue(aString = "Contains text in DIV", "Cell did not contain expected text.")
Assert.IsTrue(aDIV.Tables(0).TableRows(1).Text.Contains("Test label before:"), "Text not found in table row.")
Assert.IsTrue(aDIV.Tables(0).TableRows(1).TableCells(0).Text.Contains("Test label before:"), "Text not found in table cell.")
aBoolean = aDIV.Tables(0).TableRows(1).TableCells(0).CheckBoxes(0).Checked
aDIV.Tables(0).TableRows(1).TableCells(0).CheckBoxes(0).Checked = Not aBoolean
Assert.IsFalse(aBoolean = aDIV.Tables(0).TableRows(1).TableCells(0).CheckBoxes(0).Checked, "Checkbox not changed.")
End Using
End Sub
This test is pretty self-explanatory and requires little additional comment. Once the DIV is located and placed within a local variable (not required, but makes the syntax shorter on subsequent usage), the various elements within the DIV are proven to exist. The value of the checkbox is changed at the end of the test to demonstrate that this is possible.
The primary use of the DIV is to work with elements that cannot be located via the normal means available to the individual controls. For example: The text contained in the first row is not within an ASP.NET control, so it can only be examined by digging down into the table.
Contents: Table of Contents Previous Page: WatiN API Reference - Dispose Next Page: WatiN API Reference - Divs
This method is used to release resources no longer needed by the current instance of the browser. Normally, you can omit this statement since it is called internally by the IE instance when it closes itself.
Once Dispose is called, the IE instance is no longer valid and cannot be used. The only valid method to call on the IE instance after Dispose is Close.
Example of Usage
''' <summary> ''' Determine dispose will affect the current instance of IE. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/Default.aspx" ''' OKButton is a Private Const = "OKButton" ''' </remarks> <Test()> _ Public Sub TestDispose() Dim ErrorFlag As Boolean = False Try Dim ie As IE = New IE(currentURL) Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "The page did not contain expected text.") ie.Dispose() 'This should produce an error after IE instance is closed. Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "Error was not caused when disposed.") Catch ex As Exception ErrorFlag = True Assert.IsTrue(ex.Message.Contains("Could not find"), "Did not produce the expected error.") End Try Assert.IsTrue(ErrorFlag, "Error was not caused after dispose.") ErrorFlag = False Try Dim ie As IE = New IE(currentURL) Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "The second page did not contain expected text.") ie.Dispose() ie.Close() Catch ex As Exception ErrorFlag = True Assert.IsTrue(ex.Message.Contains("Could not find"), "Close should not produce an error.") End Try Assert.IsFalse(ErrorFlag, "Error was caused by close after dispose.") Using ie As IE = New IE(currentURL) Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "The page did not contain expected button with using.") End Using End Sub
This test shows that the Dispose statement effectively closes the current instance of the browser, because the next statement that uses the IE instance causes an error to be thrown. This could also have been checked for by using the attribute on the test for expected error, but I wanted to do some other processing afterwards, which would not have been possible using the attribute.
Note: Deliberately causing an exception so you can catch it and examine it, is normally very bad practice. You will notice how long this test takes to run as Visual Studio tries gamely to find the IE instance. I only did it here to demonstrate that nothing can be accessed from the IE instance after it is closed.
An even more important item to note in this test is the final stage, where the Using statement is employed. Using has several advantages over Dim; it ensures the proper disposal of resources, closed is not even needed, less typing, clearer syntax. You should always utilize the Using syntax when system resources are involved, such as data objects or files, to ensure proper disposal when no longer needed.
Contents: Table of Contents Previous Page: WatiN API Reference - DialogWatcher Next Page: WatiN API Reference - Div
The dialog watcher class is used to handle javascript and other dialogs. The IE instance can have a dialog watcher which can have dialog handlers assigned to it to assist in processing pop up dialogs.
Example of Usage
This is a rework of the TestAddDialogHander2 test that was introduced earlier:
''' <summary> ''' Ensure that an alert dialog will be handled and ''' closed properly. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/popup.html" ''' HelloButton is a Private Const = "hello" ''' </remarks> <Test()> _ Public Sub TestAddDialogHandler2Plus() Using ie As IE = New IE(currentURL) Dim myHandler As New AlertAndConfirmDialogHandler Dim myWatcher As New DialogWatcher(ie.ProcessID) myWatcher.Add(myHandler) ie.Button(HelloButton).ClickNoWait() Assert.IsTrue(myWatcher.Count > 0, "There should be a hello dialog open at this point.") ie.WaitForComplete() End Using End Sub
The dialog watcher is created from the IE instance and is therefore already assigned to it. A handler is added to process the javascript popup and the button is clicked to display the dialog.
Another way of using the dialog watcher is presented next:
''' <summary> ''' Ensure that an alert dialog will be handled and ''' closed properly. ''' </summary> ''' <remarks> ''' currentURL is a Private Const = ''' "http://localhost:3587/popup.html" ''' HelloButton is a Private Const = "hello" ''' </remarks> <Test()> _ Public Sub TestAddDialogHandler2Plus2() Using ie As IE = New IE(currentURL) Dim myHandler As New AlertAndConfirmDialogHandler Dim myWatcher As DialogWatcher myWatcher = ie.DialogWatcher myWatcher.Add(myHandler) ie.Button(HelloButton).ClickNoWait() Assert.IsTrue(myWatcher.Count > 0, "There should be a hello dialog open at this point.") ie.WaitForComplete() End Using End Sub
Here the dialog watcher is not created from the IE instance, so it must be specifically assigned.
Contents: Table of Contents Previous Page: WatiN API Reference - ContainsText Next Page: WatiN API Reference - Dispose
This method is used to determine if the web page has specific text being displayed. The text to be found must be in the HTML or a label control, but cannot be located within a textbox, button or other control.
Example of Usage
This is the simplest usage of the method:
''' <summary>
''' Test behavior of ContainsText
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/main.html"
''' </remarks>
<Test()> _
Public Sub TestContainsText()
Using ie As IE = New IE(currentURL)
Assert.IsTrue(ie.ContainsText("Contains text in DIV"), "Page did not contain expected text.")
End Using
End Sub
The page is examined for specified text. Frequently this is used to determine the result of some other action, such as looking for a message expected to be displayed.
This next test demonstrates that just because it can be seen, does not mean it is “contained”, or in other words, text in some controls will not be returned in the ContainsText method. The controls themselves must be examined.
''' <summary>
''' Test behavior of ContainsText
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/main.html"
''' </remarks>
<Test()> _
Public Sub TestContainsText2()
Using ie As IE = New IE(currentURL)
ie.TextField(Find.ByName("textinput1")).Value = "TestContainsText"
ie.TextField(Find.ById("Textarea1")).Value = "TextAreaText"
Assert.IsFalse(ie.ContainsText("TestContainsText"), "Textbox found when not expected.")
Assert.IsTrue(ie.TextField(Find.ById("name")).Value = "TestContainsText", "Text field did not contain expected text.")
Assert.IsFalse(ie.ContainsText("Show allert"), "Button found when not expected.")
Assert.IsTrue(ie.Button(Find.ById("helloid")).Text = "Show allert", "Button did not show expected text.")
Assert.IsTrue(ie.ContainsText("Test label before"), "Label did not contain expected text.")
Assert.IsTrue(ie.ContainsText("TextAreaText"), "Text area did not contain expected text.")
Assert.IsTrue(ie.ContainsText("First Listitem"), "List item did not contain expected text.")
End Using
End Sub
This test shows how the different controls behave in relation to ContainsText calls. Controls that will return text to ContainsText include HTML controls such as TD, label controls, lists, and text areas. Controls that will not return text to ContainsText include buttons and textboxes.
Contents: Table of Contents Previous Page: WatiN API Reference - Close Next Page: WatiN API Reference - DialogWatcher
This method is used to close the current instance of the browser. If you want to leave the browser open at the end of the test, you can omit this statement. This will allow you to examine the contents of the browser, but you will have to close it yourself. If you are running more than one test at a time, this can be somewhat aggravating, and fortunately is unnecessary just to see what the browser contains, since you can always capture a screen shot instead.
Example of Usage
''' <summary>
''' Determine if the current instance of IE will close properly.
''' </summary>
''' <remarks>
''' currentURL is a Private Const =
''' "http://localhost:3587/Default.aspx"
''' OKButton is a Private Const = "OKButton"
''' </remarks>
<Test()> _
Public Sub TestClose()
Dim ErrorFlag As Boolean = False
Try
Dim ie As IE = New IE(currentURL)
Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "The page did not contain expected text.")
ie.Close()
'This should produce an error after IE instance is closed.
Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "Error was not caused when closed.")
Catch ex As Exception
ErrorFlag = True
Assert.IsTrue(ex.Message.Contains("Could not find"), "Did not produce the expected error.")
End Try
Assert.IsTrue(ErrorFlag, "Error was not caused after close.")
Using ie As IE = New IE(currentURL)
Assert.IsTrue(ie.Button(New Regex(OKButton)).Text = "OK", "The page did not contain expected button with using.")
End Using
End Sub
This test shows that the Close statement disposes of the current instance of the browser, because the next statement that uses the IE instance causes an error to be thrown. This could also have been checked for by using the attribute on the test for expected error, but I wanted to do some other processing afterwards, which would not have been possible using the attribute.
Note: Deliberately causing an exception so you can catch it and examine it, is normally very bad practice. You will notice how long this test takes to run as Visual Studio tries gamely to find the IE instance. I only did it here to demonstrate that nothing can be accessed from the IE instance after it is closed.
An even more important item to note in this test is the second stage, where the Using statement is employed. (Yes it was hard not to say “used” here.) Using has several advantages over Dim; it ensures the proper disposal of resources, closed is not even needed, less typing, clearer syntax. You should always utilize the Using syntax when system resources are involved, such as data objects or files, to ensure proper disposal when no longer needed.
Contents: Table of Contents Previous Page: WatiN API Reference - ClearCookies Next Page: WatiN API Reference - ContainsText
I could not get this method to work as expected for me.
It is designed to clear cookies for either a specific web site or all cookies depending on whether you pass a web site URL as its parameter. When I tried it in the below test, it failed because of no security access to clear the cookie data in IE7. Since I did not want to modify system access because that did not seem proper for testing, I just decided that clearing cookies would probably not be that important.
Example of Usage
''' <summary> ''' Ensure that browser cookies do not affect ''' the results of clicking the OK Button. ''' </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 TestClearCookies() Dim StringValue As String = "" 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.Contains("OK"), "TestButtons did not find OK in the textbox after OK button clicked.") ie.CaptureWebPageToFile("c:\temp\step1.jpg") ie.SetCookie("http://google.com", "test=Cookie Test") ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test" ie.CaptureWebPageToFile("c:\temp\step2.jpg") Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.") StringValue = ie.GetCookie("http://google.com", "test") ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = StringValue ie.CaptureWebPageToFile("c:\temp\step3.jpg") ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test" ie.CaptureWebPageToFile("c:\temp\step4.jpg") ie.ClearCookies("http://google.com") ie.SetCookie("http://google.com", "test=") StringValue = ie.GetCookie("http://google.com", "test") ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = StringValue ie.CaptureWebPageToFile("c:\temp\step5.jpg") Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("test"), "Cookie data remained when should have been cleared.") End Using End Sub
This test will fail on the line with ClearCookies, because WatiN does not have access to delete cookies. If you comment out the ClearCookies command, you can change the data manually by setting the cookie to an empty string and the test will pass.
Contents: Table of Contents Previous Page: WatiN API Reference - ClearCache Next Page: WatiN API Reference - Close
This method contains some gotchas. From its method name you would think that it would clear out the system cache, at least for the web page currently being viewed, but this is a bit of a misconception.
The documentation on the WatiN site indicates that this method is used to clear the browser cache and gives an example of clearing the cache and then going back to a page that requires a login. Presumably you would have to log in again after the cache was cleared. The documentation also indicates that this may be a problem because Internet Explorer tends to keep things in memory and will ignore this method. It is suggested that the developer employ ie.ReOpen to force the browser to close and reopen, then navigate back to their desired web page to manually clear any cache at the browser level.
The gotcha is really with the system cache, however. If the web page saves information to the cache maintained on the server and then reads the value back out later, neither ClearCache nor ReOpen, nor anything else that I can find, will clear these cache values before they are set to expire by IIS.
The following test demonstrates this behavior. I modified the earlier created actions for the Default.aspx page to have the click event on the OK button to save information into cache and then the page load retrieves this information, if it exists and places it into the textbox for verification of the cache activity.
Example of Usage
The Default.aspx page used for our tests should now appear like this:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WatiNTest._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:Button ID="OKButton" runat="server" Text="OK" /> <asp:Button ID="CancelButton" runat="server" Text="Cancel" /> <asp:TextBox ID="MessageTextBox" runat="server"></asp:TextBox> <br /> <br /> <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox></div> </form></body></html>
The Default.aspx.vb code behind should appear like this:
Partial Public Class _Default Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim aValue As String = "" If Not IsPostBack Then MessageTextBox.Text = "" MessageTextBox.Focus() aValue = Cache.Get("TextMessage") If Not aValue Is Nothing Then MessageTextBox.Text = aValue & " from cache" ListBox1.Items.Add(aValue & " from cache") Else MessageTextBox.Text = "" ListBox1.Items.Add("Nothing in cache") End If End If End Sub Protected Sub CancelButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CancelButton.Click MessageTextBox.Text = "Cancel" End Sub Protected Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click MessageTextBox.Text = OKButton.Text & " clicked" ListBox1.Items.Add(OKButton.Text & " clicked") Cache.Add("TextMessage", OKButton.Text, Nothing, DateAdd(DateInterval.Hour, 1, Now), TimeSpan.Zero, CacheItemPriority.Normal, Nothing) End Sub End Class
Now the test I created looks like this:
''' <summary> ''' Ensure that browser cache does not affect ''' the results of clicking the OK Button. ''' </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 TestClearCache() Using ie As IE = New IE(currentURL) ie.ClearCache() 'Method ONE - Fully specify find criteria ie.Button(Find.ById(New Regex(OKButton))).Click() Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Contains("OK"), "TestButtons did not find OK in the textbox after OK button clicked.") ie.CaptureWebPageToFile("c:\temp\step1.jpg") ie.ClearCache() ie.TextField(Find.ById(New Regex(MessageTextBox))).Value = "Test" ie.CaptureWebPageToFile("c:\temp\step2.jpg") Assert.IsTrue(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Equals("Test"), "Textfield did not reset.") ie.ClearCache() ie.GoTo(currentURL) ie.CaptureWebPageToFile("c:\temp\step3.jpg") ie.Refresh() ie.CaptureWebPageToFile("c:\temp\step4.jpg") ie.ClearCache() ie.GoTo(currentURL) ie.CaptureWebPageToFile("c:\temp\step5.jpg") ie.GoTo("http://live.com") ie.CaptureWebPageToFile("c:\temp\step6.jpg") ie.ClearCache() ie.GoTo(currentURL) ie.CaptureWebPageToFile("c:\temp\step7.jpg") ie.ClearCache() ie.Reopen() ie.ClearCache() ie.GoTo(currentURL) ie.CaptureWebPageToFile("c:\temp\step8.jpg") Assert.IsFalse(ie.TextField(Find.ById(New Regex(MessageTextBox))).Text.Contains("cache"), "Cache data remained when should have been cleared.") End Using End Sub
As it stands, this test will fail because the text field ends up still loading its value from the cache. I left the test this way to highlight that the system cache is never cleared by the ClearCache method. To make the test run nicely with its siblings, you should change the assert to IsTrue rather than IsFalse, since that is the real expected result.
This test tries several methods to get the cache to drop the information that the OK button has been clicked. It leaves the page and returns, refreshes the page, even closes the browser and reopens it, navigating back to the default page again, all to no avail. The system cache continues to retain its value and will consistently fill the textbox with “OK from cache” until the cache is set to expire (which should be one hour from when it was clicked).
Contents: Table of Contents Previous Page: WatiN API Reference - CheckBoxes Next Page: working on it
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
More Posts
Next page »