1. 程式人生 > 其它 >資料庫實現驅動測試

資料庫實現驅動測試


public class fanwe_login_database {
//讀取資料庫的方法
public static Object[][] getTestData(String tablename) throws Exception {
//宣告MySQL的資料驅動
String diver = "com.mysql.jdbc.Driver";
//宣告資料庫的Ip地址和資料庫名稱
String url ="jdbc:mysql://IP地址:埠號/路徑";
//賬戶名密碼
String user = 使用者名稱;
String password=密碼;

//宣告儲存測試資料的list物件
List<Object[]> records = new ArrayList<Object[]>();
//設定驅動
Class.forName(diver);
//宣告連結資料庫的連結物件,使用資料庫伺服器地址,使用者名稱,密碼作為引數
Connection connection = DriverManager.getConnection(url,user,password);
//如果資料庫可用,列印成功資訊
if(!connection.isClosed()){

System.out.println("連結資料庫成功");
}
//建立statement物件
Statement statement = connection.createStatement();
String sql = "SELECT user_name FROM "+tablename+" where id >=10000";
//宣告ResultSet物件,存取執行sql語句後返回的資料結果集
ResultSet result = statement.executeQuery(sql);

//宣告一個ResultSetMetaData物件
ResultSetMetaData resultSetMetaData = result.getMetaData();
//行數
int cols = resultSetMetaData.getColumnCount();
//使用next方法變數資料結果集中的所有資料行
while (result.next()) {
int col = 0;
//宣告一個字元型陣列,按行數設定陣列大小
String fields[] = new String[cols];
for (int i = 0; i <cols ; i++) {
fields[col] = result.getString(i+1);
col++;

}

records.add(fields);
}
result.close();
statement.close();

// 將儲存測試資料的list裝換成一個object的二維陣列
Object[][] results = new Object[records.size()][];
for (int i = 0; i <records.size() ; i++) {
results[i] = records.get(i);
}
return results;

}
//呼叫獲取object二維陣列的資料的方法
@DataProvider(name = "testData")
public Object[][] getData() throws Exception {
return getTestData("fanwe_user");
}

//讀取資料庫使用者名稱,批量登入
@Test(dataProvider = "testData")
public void Login_database(String loginName) throws Exception {
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://192.168.232.138/fanwe/index.php?ctl=user&act=dologin&fhash=TDgVAYxwiNcSRoQVJLMltGilpDmXCaOSWYUzpoTtkeVaBIROhf");
//設定請求頭
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//請求引數
String param = "email="+loginName+"&user_pwd=eGhJQ2hmQXdFUWRxanRhY2habEJMR1hUSVBrVmtTSWRDaHRqdm5PV21IWGxFc3ZTcWclMjV1NjVCOSUyNXU3RUY0Y3h5MTIzNDU2JTI1dThGNkYlMjV1NEVGNg==&ajax=1";
StringEntity entity =new StringEntity(param);
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
//將響應結果裝換成json
JSONObject jsonObject = new JSONObject(result);
jsonObject.get("status");
int status = (int) jsonObject.get("status");
String info = (String) jsonObject.get("info");
System.out.println("status: "+status+" info: "+info);
Assert.assertEquals(2,status);

}
}