本案例将使用Testng框架
数据由.csv文件提供
下面我们直接看代码:
package selenium_01;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Sjqd {
WebDriver dr;
String URL="http:\\192.168.8.200";
@Test(dataProvider="sj")
public void f(String user,String password) throws InterruptedException {
dr.get(URL);
dr.findElement(By.id("zentao")).click();
Thread.sleep(1000);
dr.findElement(By.id("account")).sendKeys(user);
dr.findElement(By.name("password")).sendKeys(password);
dr.findElement(By.id("submit")).click();
Thread.sleep(2000);
//下面的几部是为了判断登录是否成功用的
String aString=dr.getCurrentUrl();
String s="my";
if (aString.contains(s)) {
System.out.println("用户名为 :"+user+" 密码为 :"+password+" 的用户登录成功");
}else {
System.out.println("用户名为 :"+user+" 密码为 :"+password+" 的用户登录失败");
}
dr.get(URL);
Thread.sleep(3000);
}
@DataProvider(name="sj")
public Object[][] Data() throws IOException{
return CSV();
}
@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","C:\\Users\\Administrator\\Desktop\\浏览器\\浏览器驱动\\chromedriver.exe");
dr=new ChromeDriver();
dr.manage().window().maximize();
}
@AfterTest
public void afterTest() {
dr.quit();
}
//此方法用来读取一个csv文件,并将文件中的数据存储在一个二维数组中
public static Object[][] CSV() throws IOException {
ArrayList<Object> list=new ArrayList<Object>();
BufferedReader in=new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\Data.csv"));
in.readLine();
String a=null;
while((a=in.readLine())!=null) {
String b[]=a.split(",");
list.add(b);
}
in.close();
Object[][] ob=new Object[list.size()][];
for(int i=0;i<list.size();i++) {
ob[i]=(Object[]) list.get(i);
}
return ob;
}
}
大家可以看到Neon这里做的比较粗,弹出框没做处理还有很多很多的地方没有做优化。我们还可以是用page设计模式还可以封装啊抽取啊等等。
这里主要是为了能让大家看明白,更容易理解。
大家呢多看看代码多想想,其实都很好理解的,唯一不好理解就是那个二维数组那块,所以大家没事还是要经常复习一下基础知识呢。哈哈 欢迎大家指出Neon的不足,让我们共同进步。