本人在學習使用selenium2java的過程中,遇到過需要測試方案購買的問題,每次買完之後都得手動清除一下數據,重新測試購買流程。在寫自動化用例的時候用到了數據庫相關方法,分享一下,供參考。
//購買志願方案(使用兌換卡)
public static void buyWishProjectByCoupon(WebDriver driver) throws ClassNotFoundException, SQLException, IOException, InterruptedException {
MySql.UpdateOrderStutas(user_id);//使用戶當前已購買訂單過期
findElementByIdAndClick(driver, "btnIndexPay");//點擊購買
findElementByXpathAndClick(driver, ".//*[@id='payment_channel']/li[1]");//點擊兌換卡購買
findElementByIdAndClick(driver, "btnOrderCreatePay");//點擊立即支付
/*如果用戶之前購買過,則在第一行設置爲過期
* 如果用戶之前生成過訂單,會提示雷同,跳轉訂單頁面,繼續選擇兌換卡支付
* 如果用戶沒有購買過或者訂單全部過期,直接使用兌換卡支付
*/
if (exists(driver, By.className("confirm"))) {
sleep(0);
findElementByClassNameAndClick(driver, "confirm");
findElementByTextAndClick(driver, "立即支付");
findElementByIdAndClick(driver, "btnOrderCreatePay");//點擊立即支付
payByCoupon(driver);
}else{
payByCoupon(driver);
}
driver.get("http://172.21.134.15:5555/purchase/order/list");//跳轉我的訂單頁面
refresh(driver);//強制刷新
String status = getTextByClassName(driver, "pull-right");//獲取最新訂單狀態
assertTrue("購買課程失敗!", status.equals("已付款"));
}
下面是使用兌換卡的方法:
//兌換卡支付
public static void payByCoupon(WebDriver driver) throws ClassNotFoundException, SQLException {
String coupon_id = MySql.getCouponIdAndPassword();//獲取帳號
findElementByIdAndClearSendkeys(driver, "input-coupon_number", coupon_id);//輸入帳號
findElementByIdAndClearSendkeys(driver, "input-coupon_password", "123456");//輸入密碼
findElementByXpathAndClick(driver, ".//*[@id='modal-pay_card']/div/div/div[2]/div/div/div[2]/div/div[4]/div/button");//點擊支付
}
下面是修改用戶訂單狀態的方法:
//修改用戶訂單狀態
public static void UpdateOrderStutas(int id) throws ClassNotFoundException, SQLException, IOException {
// 加載驅動程序
Class.forName(driver);
// 連接數據庫
Connection connection = DriverManager.getConnection(url, user, password);
if(!connection.isClosed()){
Statement statement = connection.createStatement();
//1是代付款,2是已付款,5是已過期
String sql = "UPDATE op_orders SET order_status = 5 where user_id = "+id+" and order_status= 2";
statement.executeUpdate(sql);
connection.close();
}else {
output("failed connecting to the Database!");
}
}
下面是獲取尚未使用的兌換卡的方法:
//查找尚未使用的兌換卡帳號和密碼
public static String getCouponIdAndPassword() throws SQLException, ClassNotFoundException {
String coupon_id = null;
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
if (!connection.isClosed()) {
Statement statement = connection.createStatement();
String sql = "SELECT * FROM op_coupon LEFT JOIN op_coupon_used on op_coupon.coupon_id = op_coupon_used.coupon_id WHERE op_coupon_used.order_no is null limit 1";
ResultSet result = statement.executeQuery(sql);
// output("帳號"+"\t"+"密碼");
while(result.next()){
coupon_id = result.getString("serial_no");
// output(result.getString("serial_no")+"\t"+result.getString("serial_password"));
}
result.close();
connection.close();
}
return coupon_id;
}