前提:使用upfile.html模拟测试文件上传功能
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>upload_file</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css"
rel="stylesheet" />
</head>《Selenium2 Java 自动化测试实战》
102
<body>
<div class="row-fluid">
<div class="span6 well">
<h3>upload_file</h3>
<input type="file" name="file" />
</div>
</div>
</body>
<script
src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script>
</html>
第一种方法:使用driver.findElement(By.name("file").sendKeys("xxx.txt");//上传xxx.txt文件
第二种方法,使用第三方软件AutoIt模拟选择文件上传功能,
在SciTE Script Editor编写脚本:
ControlFocus("文件上传", "","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("文件上传", "","Edit1", “xxx.txt”)
Sleep(2000)
ControlClick("文件上传", "","Button1");
保存为*.au3文件,再使用Compile Script to exe转换为exe程序,然后编写程序调用该程序:
Runtime rm=Runtime.getRuntime(); try { rm.exec("C:\\Users\\Administrator\\Desktop\\test.exe"); }catch(IOException e) { e.printStackTrace(); }
如果希望上传的文件是可以随时变化的,需要将文件名变为变量,修改AutoIt脚本为:
ControlFocus("文件上传", "","Edit1")
WinWait("[CLASS:#32770]","",10)
ControlSetText("文件上传", "","Edit1", $CmdLine[1])
Sleep(2000)
ControlClick("文件上传", "","Button1");
修改Java调用程序为:
Runtime rm=Runtime.getRuntime(); try { rm.exec("C:\\Users\\Administrator\\Desktop\\test.exe D:\\xxx.txt");//将文件名上传变为参数 }catch(IOException e) { e.printStackTrace(); }