SELENIUM Bài 9: Data Provider trong TestNG Framework

 

 I. Data Provider

1. Data Provider là gì ?

Data Provider giúp chúng ta truyền data vào test case, data truyền vào sẽ ở dưới dạng mảng của object, mỗi một cái hàng trong mảng đó thì nó sẽ được chạy thành một testcase, giống như chúng ta load data từ trong một file excel, mỗi dòng trong một file excel thì nó sẽ chạy thành một test case riêng.

Hình 1: Data Provider trong TestNG

2. Cách sử dụng Data Provider

Để sử dụng Data Provider chúng ta sẽ dùng cú pháp là @DataProvider, chúng ta sẽ phải khai báo một cái data provider

Ví dụ: 
@DataProvider(name = "Authentication") // Tên của Data Provider là "Authentication"
public static Object[][] credentials() {
return new Object[][] { { "testuser_1", "Test@123" }, { "testuser_1", "Test@123" }};
}
// Sau cái tên của Data Provider chúng ta phải khai báo một cái hàm của có kiểu trả về là một mảng Object[][]

Sau đó ở trong cái test của chúng ta chỗ nào cần sử dụng data thì chúng ta sẽ khai báo test dùng cái Data Provider nào.

@Test(dataProvider = "Authentication") // Khai báo trong Test
public void test(String sUsername, String sPassword) { // Truyền tham số tương ứng với Data Provider
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");
driver.findElement(By.xpath(".//*[@id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys(sUsername);
driver.findElement(By.id("pwd")).sendKeys(sPassword);
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath(".//*[@id='account_logout']/a")).click();
driver.quit();
}
}
Data Provider của chúng ta có báo nhiêu dòng, thì nó sẽ chạy thành bấy nhiêu test case.

3. Ví dụ về Data Provider

VÍ DỤ 1 Đề bài: Mở trang web http://automationpractice.com/index.php đăng nhập sau đó đăng xuất sử dụng TestNG Framework có sử dụng Data Provider

  • Bước 1: Tạo 1 project mới tên là BlogTestNGFirstTest, import toàn bộ thư viện của selenium vào build path, ngoài ra còn phải add thêm file jquery-3.5.1.jar để tránh bị báo lỗi, các bạn có thể download file này TẠI ĐÂY, trong project này sẽ tạo một package là tests
  • Bước 2: Chuột phải vào package tests chọn New - Other - TestNG Class - Next - Điền class name là LoginDataProvider- Tích chọn anotation @BeforeMethod, @AfterMethod  và Data Provider - XML Suite file: điền LoginDataProvider.xml - Nhấn Finish
  • Bước 3: Code theo framework TestNG và đây là nội dung file code và giải thíchFile LoginDataProvider.java

package tests;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;

public class LoginDataProvider {
WebDriver driver;

@Test(dataProvider = "LoginData") // Chỗ này khai báo tên Data Provider chúng ta muốn dùng
public void loginSuccessfulTest(String username, String password) {
driver.findElement(By.className("login")).click();
driver.findElement(By.id("email")).sendKeys(username);
driver.findElement(By.id("passwd")).sendKeys(password);
driver.findElement(By.id("SubmitLogin")).click();
driver.findElement(By.className("logout")).click();
}

//@BeforeMethod thường để setup các môi trường
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver",
"D:\\Work\\Automation Test\\Selenium\\Tool\\Selenium\\Library\\Selenium-java-3.141.59 and Driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://automationpractice.com/index.php");
}

// @AfterMethod thường đưa vào các hàm teardown để giải phóng môi trường
@AfterMethod
public void afterMethod() {
driver.quit();
}

@DataProvider(name = "LoginData") //Khai báo tên Data Provider
public Object[][] loadLoginData() { // Hàm loadLoginData có kiểu trả về là một mảng Object
return new Object[][] { { "hocautotest@gmail.com", "12345678" }, { "hocautotest@gmail.com", "1234567" } }; // Cái này là dữ liệu chúng ta fix cứng sẵn để test
}

}

VÍ DỤ 2 Đề bài: Áp dụng Data Provider để đọc Data từ trong file excel.

  • Bước 1: Tạo 1 project mới tên là BlogTestNGFirstTest, import toàn bộ thư viện của selenium, apache poi vào build path, ngoài ra còn phải add thêm file jquery-3.5.1.jar để tránh bị báo lỗi, các bạn có thể download file này TẠI ĐÂY, trong project này sẽ tạo các package là tests và utils chứa 2 file Constants.java và ExcelUtils.java, các bạn có thể down load 2 file utils đó TẠI ĐÂY 
  • Bước 2: Chuột phải vào package tests chọn New - Other - TestNG Class - Next - Điền class name là LoginTestExcelProvider- Tích chọn anotation @BeforeMethod, @AfterMethod  và Data Provider - XML Suite file: điền LoginTestExcelProvider.xml - Nhấn Finish
  • Bước 3: Chọn new Folder - điền tên Folder là Data, trong folder này sẽ chứa file LoginTest.xlsx nội dung file sẽ có chứa dữ liệu username, password, kết quả mong muốn và kết quả thực tế. Tài khoản này các bạn có thể tự tạo hoặc, các bạn có thề tải file chưa tài khoản đó TẠI ĐÂY
  • Bước 4: Code theo framework TestNG và đây là nội dung file code và giải thích File LoginTestExcelProvider.java
package tests;

import org.testng.annotations.Test;

import utils.Constants;
import utils.ExcelUtils;

import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;

public class LoginTestExcelDataProvider {
WebDriver driver;


@Test(dataProvider = "LoginDataExcel") 
public void loginSuccessfulTest(String testcaseID, String username, String password, String expected) throws Exception {

// Test case sẽ phải truyền vào 4 biến tương ứng với cột trong file Data LoginTest.xlsx
driver.findElement(By.className("login")).click();
driver.findElement(By.id("email")).sendKeys(username);
driver.findElement(By.id("passwd")).sendKeys(password);
driver.findElement(By.id("SubmitLogin")).click();
ExcelUtils excel1 = new ExcelUtils(Constants.DATA_LOGIN_PATH, Constants.DATA_LOGIN_SHEET); 

// Đối tượng excel ở dưới không dùng được ở trên testcase này nên chúng ta khai báo lại một đối tượng excel1 mới.

// Dưới đây là một loạt các if else để ghi dữ liệu vào cột result
try {
driver.findElement(By.className("logout")).click();
if (expected.equalsIgnoreCase("pass")) { 

//Nếu mà kết quả trong cột expected mà giống với "pass" thì đền pass vào cột result
excel1.setCellData("pass", excel1.getRowContains(testcaseID, Constants.COL_LOGIN_TESTCASEID),Constants.COL_LOGIN_RESULT);

// Hàm setCellData() với 3 tham số là Chuỗi muốn ghi vào, số hàng, số cột

// Để lấy số hàng chúng ta dùng hàm getRowContains() với 2 tham số truyền vào là TestCaseID và sốt cột của TestCaseID với giá trị là 0

//Số cột của cột Result trong test case này được chứa trong hằng số Constants.COL_LOGIN_RESULT với giá trị là 4

} else {
// Ngược lại thì điền fail vào cột result

excel1.setCellData("fail", excel1.getRowContains(testcaseID, Constants.COL_LOGIN_TESTCASEID),Constants.COL_LOGIN_RESULT);
Assert.fail("Login successful but expected result is fail");
}
} catch (Exception e) {

// Trong catch thì ngược lại với try
if (expected.equalsIgnoreCase("fail")) {
excel1.setCellData("pass", excel1.getRowContains(testcaseID, Constants.COL_LOGIN_TESTCASEID),Constants.COL_LOGIN_RESULT);
} else {
excel1.setCellData("fail", excel1.getRowContains(testcaseID, Constants.COL_LOGIN_TESTCASEID),Constants.COL_LOGIN_RESULT);
Assert.fail("Login unsuccessful but expected result is pass");
}
}

}

// @BeforeMethod thường để setup các môi trường
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver",
"D:\\Work\\Automation Test\\Selenium\\Tool\\Selenium\\Library\\Selenium-java-3.141.59 and Driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(Constants.BASE_URL);
}

// @AfterMethod thường đưa vào các hàm teardown để giải phóng môi trường
@AfterMethod
public void afterMethod() {
driver.quit();
}

@DataProvider(name = "LoginDataExcel")
// Đây là hàm load dữ liệu từ file excel
public Object[][] loadExcelData() throws Exception { 
ExcelUtils excel = new ExcelUtils(Constants.DATA_LOGIN_PATH, Constants.DATA_LOGIN_SHEET);
return excel.getTableArray(4); 

// Hàm getTableArray() load toàn bộ 4 cột dữ liệu trong file LoginTest.xlsx, các bạn có thể xem thêm nội dung hàm này trong file  ExcelUtils.java

}
}

Giới thiệu về HIENDV94

Mình là Hiển. Đây là blog ghi chép lại những thứ mình trải qua và học được hàng ngày, mình luôn luôn muốn học hỏi để trau dồi kinh nghiệm, hoàn thiện bản thân. Rất mong được làm quen mọi người. Hãy kết bạn với mình qua Facebook các bạn nhé.

0 Bình luận:

Đăng nhận xét