实验2:Selenium的安装以及测试以及WebDriver
1.安装Selenium
1.1 下载firefox 40.0,然后使用firefox打开百度搜索Selenium add-ons,打开第一个结果,默认安装Selenium。

2.录制以及保存脚本
首先打开Selenium, 访问网站http://121.193.130.195:8080/,使用学号以及密码登录,完成录制;


3. 编写Selenium Java WebDriver 程序,并测试学号与git地址的对应关系。
在Selenium中选择文件->Export test case as ->Java Juint4 Webdriver,生成一个java文件。

打开Eclipse新建一个java project,并且添加libs下的jar包。
新建一个class将上面生成的代码拷贝进去并进行修改;
代码为:
package lab2;
import java.nio.charset.Charset;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import com.csvreader.CsvReader;
public class test {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String id = null;
private String pwd = null;
private String gitUrl = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://121.193.130.195:8080";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGit() throws Exception {
CsvReader cin = new CsvReader("F:/inputgit.csv", ',',Charset.forName("GBK"));
cin.readHeaders();
while(cin.readRecord()){
id = cin.get(0);
pwd = id.substring(4, 10);
gitUrl = cin.get(2);
driver.get(baseUrl + "/");
driver.findElement(By.id("name")).clear();
driver.findElement(By.id("name")).sendKeys(id);
driver.findElement(By.id("pwd")).clear();
driver.findElement(By.id("pwd")).sendKeys(pwd);
driver.findElement(By.id("submit")).click();
String gitUrls = driver.findElement(By.xpath("//tbody[@id = 'table-main']/tr[3]/td[2]")).getText();
if (!gitUrl.equals(gitUrls)){
System.out.println(id);
System.out.println(gitUrl);
System.out.println(gitUrls);
continue;
}
assertEquals(gitUrl,gitUrls);
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
运行结果如下:

一共花费时间308s。

浙公网安备 33010602011771号