ie = (InternetExplorer)allBrowsers.Item(0);
你實際采用何種方法取決于你的實際測試場景。既然我建立了我的測試InternetExplorer對象,我能注冊我之前提到的DocumentComplete事件句柄:
ie.DocumentComplete += new
DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
簡單來說,當InternetExplorer的DocumentComplete事件發生時,調用用戶定義的ie.DocumentComplete方法。如果你回頭去看圖3中的代碼,你能看到我如此定義了該方法:
private static void ie_DocumentComplete(object pDisp, ref object URL)
{
documentComplete.Set();
}
ie_DocumentComplete 方法調用了我早些時候在測試類中定義的AutoResetEvent對象中的Set方法。簡而言之,現在我能暫停我的執行線程,直到我的InternetExplorer對象充分裝載了。我會立即向你展示怎樣具體做這件事情?,F在我瀏覽正在進行測試的Web應用程序,等到應用程序充分裝載:
Console.WriteLine("\nNavigating to the Web app");
object missing = Type.Missing;
ie.Navigate("http://localhost/LowLevelWebUIAutomationApp/WebForm1.aspx",
ref missing, ref missing, ref missing, ref missing);
documentComplete.WaitOne();
我使用InternetExplorer.Navigate方法來裝載我的Web應用程序。Navigate接受數個可選參數,但是在這個例子中,我不需要任何參數。注意,我調用了documentComplete對象的WaitOne方法。WaitOne將停止我的執行線程,直到應用程序充分裝載到了Internet Explorer中。在這個例子中,我沒有提供一個超時值,所以我會不停的等待,但你很可能會向WaitOne傳遞一個代表超時毫秒數的整型值。下一步我設定Internet Explorer為一個固定的大小,并獲得Web應用程序文檔的一個引用。
Console.WriteLine("Setting IE to 525x420");
ie.Width = 525;
ie.Height = 420;
HTMLDocument theDoc = (HTMLDocument)ie.Document;
我聲明了一個HTMLDocument變量,并為它指定了一個值。HTMLDocument接口是在mshtml名字空間中定義的。我怎么知道呢?圖4是Visual Studio .NET對象瀏覽器的一個屏幕截圖。我擴展mshtml interop到匯編層,看到了它們的所有接口、類、事件和其他對象。
圖 4對象瀏覽器
下一步,我模擬了對“Last Name”單選按鈕的檢查,向文本框控件中輸入“urk”:
Console.WriteLine(
"\nSelecting ''Last Name'' radio button");
HTMLInputElement radioButton =
(HTMLInputElement)theDoc.getElementById("RadioButtonList1_0");
radioButton.@checked = true;
Console.WriteLine("Setting text box to ''urk''");
HTMLInputElement textBox =
(HTMLInputElement)theDoc.getElementById("TextBox1");
textBox.value = "urk";
這兩段代碼是非常相似的,并且看起來相當明白。我通過getElementByID方法獲得了HTMLInputElemen對象的引用。在擁有這個對象之后,我能使用它的屬性或方法來操縱它。這里我選擇單選按鈕控件的“checked”屬性(因為在C#中checked是一個保留字,我必須使用“@checked”)和文本框控件的“value”屬性。按你下面看到的方式點擊Search按鈕:
Console.WriteLine("Clicking search button");
HTMLInputElement button =
(HTMLInputElement)theDoc.getElementById("Button1");
button.click();
documentComplete.WaitOne();
在這個例子中,我需要調用WaitOne方法來確保表示搜索結果的頁面被充分裝載了。通過一些很小的實驗,你會發現你能虛擬操縱任何HTML元素。例如,我能模擬下拉框的選擇、超鏈接的點擊,當然在這個測試場景中我無需這樣做。在我操作Web應用程序之后,我必須檢查最終狀態的正確性。
Console.WriteLine("\nSeeking ''Burke, Brian'' in list box");
HTMLSelectElement selElement =
(HTMLSelectElement)theDoc.getElementsByTagName(
"select").item(0, null);
if (selElement.innerText.ToString().IndexOf("Burke, Brian") >= 0)
{
Console.WriteLine("Found target string");
pass = true;
}
else
{
Console.WriteLine("*Target string not found*");
}
一般模式是通過共同的標簽名獲得一個HTML元素集的引用,然后使用屬性得到某一特定元素,然后獲取表示該元素頭標簽和尾標簽之間數據串的innerText。這里,我獲得了所有元素——當然,也是我的Web頁面中唯一的