软件测试Lab2:SeleniumIDE使用及编写Selenium Java WebDriver
一、安装SeleniumIDE插件
firefox版本是42.0,selenium版本是2.9.1。(解决版本兼容问题搞了很久…)
注意:将firefox更新设置为不自动更新!!!
二、使用SeleniumIDE录制脚本和导出脚本及进入系统查看github地址
导出时文件->export test case as -> Java/junit4 webdriver即可得到相应的java文件。
三、编写Selenium Java WebDriver程序,测试表格中学号和github地址是否对应
测试代码:
1 package com.testing.selenium; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.nio.charset.Charset; 6 7 import java.util.regex.Pattern; 8 import java.util.concurrent.TimeUnit; 9 import org.junit.*; 10 import static org.junit.Assert.*; 11 import static org.hamcrest.CoreMatchers.*; 12 import org.openqa.selenium.*; 13 import org.openqa.selenium.firefox.FirefoxDriver; 14 import org.openqa.selenium.support.ui.Select; 15 import static org.junit.Assert.*; 16 17 import com.csvreader.CsvReader; 18 19 public class SeleniumCheck { 20 private WebDriver driver; 21 private String baseUrl; 22 private boolean acceptNextAlert = true; 23 private StringBuffer verificationErrors = new StringBuffer(); 24 static Thread th = new Thread(); 25 26 @Before 27 public void setUp() throws Exception { 28 driver = new FirefoxDriver(); 29 baseUrl = "https://psych.liebes.top"; 30 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 31 } 32 33 @Test 34 public void testSelenium() throws Exception { 35 CsvReader r = new CsvReader("/Users/yang/Documents/se/EclipseProjects/Lab02/input.csv",',',Charset.forName("utf-8")); 36 r.readHeaders(); 37 while (r.readRecord()) { 38 39 String name = r.get("id"); 40 if(name.equals("")) 41 break; 42 String pwd = name.substring(name.length() - 6); 43 String github = r.get("github"); 44 driver.get(baseUrl+"/st"); 45 Thread.sleep(500); 46 driver.findElement(By.id("username")).sendKeys(name); 47 driver.findElement(By.id("password")).sendKeys(pwd); 48 driver.findElement(By.id("submitButton")).click(); 49 String github2 = driver.findElement(By.cssSelector("p.login-box-msg")).getText(); 50 if(!github.equals(github2)) 51 System.out.println(name); 52 else 53 { 54 assertEquals(github,github2); 55 } 56 57 } 58 r.close(); 59 } 60 61 @After 62 public void tearDown() throws Exception { 63 driver.quit(); 64 String verificationErrorString = verificationErrors.toString(); 65 if (!"".equals(verificationErrorString)) { 66 fail(verificationErrorString); 67 } 68 } 69 70 private boolean isElementPresent(By by) { 71 try { 72 driver.findElement(by); 73 return true; 74 } catch (NoSuchElementException e) { 75 return false; 76 } 77 } 78 79 private boolean isAlertPresent() { 80 try { 81 driver.switchTo().alert(); 82 return true; 83 } catch (NoAlertPresentException e) { 84 return false; 85 } 86 } 87 88 private String closeAlertAndGetItsText() { 89 try { 90 Alert alert = driver.switchTo().alert(); 91 String alertText = alert.getText(); 92 if (acceptNextAlert) { 93 alert.accept(); 94 } else { 95 alert.dismiss(); 96 } 97 return alertText; 98 } finally { 99 acceptNextAlert = true; 100 } 101 } 102 }
最终输出有错误的学号: