WatiN——Web自动化测试(三)【弹出窗口处理】
public static void CaptureAlertDialog(this Browser browser, Action<AlertDialogHandler> operation, int waitTimeInSeconds)
{
var handler = new AlertDialogHandler();
using (new UseDialogOnce(browser.DialogWatcher, handler))
{
operation(handler);
handler.WaitUntilExists(waitTimeInSeconds);
if (handler.Exists())
handler.OKButton.Click();
}
}
context.Browser.CaptureAlertDialog((AlertDialogHandler handler) => { btn.WaitUntilExistsAndClickNoWait(context.TestConfig.Timeout); }, 5);
btn.WaitUntilExistsAndClickNoWait(context.TestConfig.Timeout); 为button的点击事件。
public static void CaptureConfirmDialog(this Browser browser, Action<ConfirmDialogHandler> operation, int waitTimeInSeconds)
{
var handler = new ConfirmDialogHandler();
using (new UseDialogOnce(browser.DialogWatcher, handler))
{
operation(handler);
handler.WaitUntilExists(waitTimeInSeconds);
if (handler.Exists())
{
handler.OKButton.Click();//确认按钮 handler.CancelButton.Click();取消按钮
}
}
}
context.Browser.CaptureConfirmDialog((ConfirmDialogHandler handler) =>
{
btn.WaitUntilExistsAndClickNoWait(context.TestConfig.Timeout);
}, 5);
btn.WaitUntilExistsAndClickNoWait(context.TestConfig.Timeout);为Button点击事件
var btn = "获取button按钮";
var fileName = System.Windows.Forms.Application.StartupPath + "保存路径文件名";
FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(fileName);
using (new UseDialogOnce(context.Browser.DialogWatcher, fileDownloadHandler))
{
btn.WaitUntilExistsAndClickNoWait(context.TestConfig.Timeout);
context.Browser.WaitUntil(5);
fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(60);
fileDownloadHandler.WaitUntilDownloadCompleted(200);
}
首先需要将主浏览器对象进行保存,让这个browser对象再打开新窗口,从中获取窗口页面的URL
如下代码:
var orginBrowser = context.Browser;//context.Browser浏览器对象
try
{
Div.Button(btn => btn.ClassName == "ButtonStyle").WaitUntilExistsAndClick(context.TestConfig.Timeout);//Button按钮,进行onclick事件
context.Browser.WaitUntil(3);//等待3秒
context.Browser = WatiN.Core.Browser.AttachTo(context.Browser.GetType(), Find.ByUrl(url => url.IndexOf("页面名称") > -1), context.TestConfig.Timeout);//查找新窗口的页面名称
context.Browser.Refresh();//进行刷新
///
///对窗口中的内容进行操作
///
context.Browser.Close();
}
catch { }
context.Browser = orginBrowser;