[Selenium With C# 基础教程] Lesson13-弹出窗口

在本节,将介绍Web页面常见和一些弹出窗口,如上传文件弹出窗口。而大部分的弹出窗口,如选择和上传文件,大都使用的是本地的Windows窗口,而Selenium仅能操作浏览器,这样就对测试形成了挑战。Selenium API处理弹出窗口的主要是IAlert接口,详细如下所示:

13-3 IAlert类.jpg

文件上传

下图是一种常见的文件上传弹出窗口:

13-1 文件上传示例_c2i.jpg

HTML源码如下:

<body>
  请选择上传文件:<input type="file" name="fileUpload" id="fileUpload" size="50" />
</body>

相应的定位代码如下:

    string filePath = @"C:\类和对象.jpg";
    driver.FindElement(By.Id("fileUpload")).SendKeys(filePath);

在以上的代码里面,直接将上传的文件路径写成绝对路径了,这样做灵活性不够,扩展性较差,并不推荐。建议在做测试的时候,将测试文件放在测试项目里面,这样我们就可以使用相对路径来选择文件。示例代码如下:

string filPath = MyClass.GetFilePath() + @"testData\类和对象.jpg";
driver.FindElement(By.Id("fileUpload")).SendKeys(filePath);

JavaScript弹出窗口

JavsScript弹出窗口是通过使用Javascript创建,主要用来确认操作和提示消息。一种常见的弹出框如下所示:

13-2 弹出窗口示例.jpg

HTML源码如下:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<script type="text/javascript">
    function show_confirm() 
    {
        var r = confirm("请点击");
    }
</script>
</head>
<body>
    请选择上传文件: <input type="file" name="fileUpload" id="fileUpload" size="50" />
    <br /><br />
    <input type="button" onclick="show_confirm()" value="显示确认对话框" />
</body>
</html>

定位示例代码:

  • 方法一:使用Selenium API中的IAlert接口
    driver.FindElement(By.XPath("//input[@value='显示确认对话框']")).Click();
    IAlert alert = driver.SwitchTo().Alert();
    if (alert.Text.Contains("请点击"))
    {
        alert.Accept();
    }
    else
    {
        alert.Dismiss();
    }
  • 方法二:使用JavaScript
((IJavaScriptExecutor)driver).ExecuteScript("window.confirm=function(){return true;}");
((IJavaScriptExecutor)driver).ExecuteScript("window.alert=function(){return true;}");
((IJavaScriptExecutor)driver).ExecuteScript("window.prompt=function(){return true;}");
driver.FindElement(By.XPath("//input[@value='显示确认对话框']")).Click();

模态对话框

随着JavaScript的发展,出现一些非常灵活易用的JavaScript库,如Bootstrap,这些JavaScript库逐渐替换了Javascript默认的提示框。一种典型的对话框如下所示:

13-4 模态对话框示例_c2i.jpg

相比较好于原生态的JavaScript提示框,对于模态对话框,写测试脚本要容易很多,示例代码如下:

driver.FindElement(By.Id("modalpopup")).Click();
Thread.Sleep(500);
driver.FindElement(By.XPath("//button[contains(@class,'btn btn-default')]")).Click();

设定超时时间

在测试过程中,弹出窗口未及时处理,将导致测试失败。对于这种情况,我们通过给测试方法添加属性TimeoutAttribute来指定最长的时间。

    [TestMethod]
    [Timeout(10*1000)] //超时时间为10秒
    public void TestModalPopUp()
    {
     //实现代码
    }

在执行用例时,如果超出设定的时间,会出现以下报错
Test 'TestModalPopUp' exceeded execution timeout period.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容