package testNGWithDataDriven;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestNGDBDriven {
public WebDriver driver;
String baseUrl = "http://www.sogou.com";
@DataProvider(name="testdata")
public static Object[][] words() throws IOException{
return getTestData("testdata");
}
@Test(dataProvider = "testdata")
public void testSearch(String searchWord1, String searchWord2, String searchResult){
driver.get(baseUrl + "/");
driver.findElement(By.id("query")).sendKeys(searchWord1+" "+searchWord2);
driver.findElement(By.id("stb")).click();
Assert.assertTrue(driver.getPageSource().contains(searchResult));
}
@BeforeMethod
public void beforeMethod(){
driver = new ChromeDriver();
}
@AfterMethod
private void afterMethod(){
driver.quit();
}
public static Object[][] getTestData(String tablename) throws IOException{
//聲明Mysql資料庫的驅動
String dbDriver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/testng?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String user = "root";
String password = "root";
//聲明存儲測試資料的List對象
List<Object[]> records = new ArrayList<Object[]>();
try{
//設定驅動
Class.forName(dbDriver);
Connection conn = DriverManager.getConnection(url,user,password);
if (!conn.isClosed())
System.out.println("連接配接資料庫成功");
//建立statement對象
Statement statement = conn.createStatement();
//拼接sql語句
String sql = String.format("Select * from %s", tablename);
//聲明結果集對象rs,用于存儲執行sql語句傳回的資料結果集
ResultSet rs = statement.executeQuery(sql);
//聲明一個ResultSetMetaData對象
ResultSetMetaData rsMetaData = rs.getMetaData();
//調用ResultSetMetaData對象的getColumnCount方法擷取資料行的列數
int cols = rsMetaData.getColumnCount();
/**使用next方法周遊資料結果集中的所有資料行*/
while (rs.next()){
//聲明一個字元串型數組,數組大小使用資料行的列個數進行聲明
String fields[] = new String[cols];
int col = 0;
//周遊所有資料行中的所有資料,并存儲在字元串數組中
for (int colIdx = 0; colIdx<cols; colIdx++){
fields[col] = rs.getString(colIdx+1);
col++;
}
//将每一行的資料存儲到字元串數組後,存儲到records中
records.add(fields);
//輸出資料行中的前三列内容,用于驗證資料庫内容是否正确讀取
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
//關閉資料結果集對象
rs.close();
//關閉資料庫連接配接
conn.close();
}catch (ClassNotFoundException e){
System.out.println("未能找到Mysql的驅動類");
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
//定義函數傳回值,即Object[][]
//将存儲測試資料的list轉換為一個Object的二維數組
Object[][] results = new Object[records.size()][];
//設定二維數組每行的值,每行是一個Object對象
for (int i = 0; i<records.size(); i++){
results[i] = records.get(i);
}
return results;
}
}