編寫TestNG用例測試基本上包括以下步驟:
· 編寫業(yè)務(wù)邏輯
· 針對業(yè)務(wù)邏輯中涉及的方法編寫測試類,在代碼中插入TestNG的注解
· 直接執(zhí)行測試類或者添加一個testng.xml文件
· 運行 TestNG.
下面我們介紹一個完整的例子來測試一個邏輯類;
1.創(chuàng)建一個pojo類EmployeeDetail.java
public class EmployeeDetail {
private String name;
private double monthlySalary;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the monthlySalary
*/
public double getMonthlySalary() {
return monthlySalary;
}
/**
* @param monthlySalary the monthlySalary to set
*/
public void setMonthlySalary(double monthlySalary) {
this.monthlySalary = monthlySalary;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
EmployeeDetail用來:
· get/set 員工的名字的值
· get/set 員工月薪的值
· get/set員工年齡的值
2.創(chuàng)建一個EmployeeLogic.java
public class EmployeeLogic {
// Calculate the yearly salary of employee
public double calculateYearlySalary(EmployeeDetail employeeDetails){
double yearlySalary=0;
yearlySalary = employeeDetails.getMonthlySalary() * 12;
return yearlySalary;
}
}
EmployeeLogic.java用來:
計算員工年工資
3.創(chuàng)建一個測試類,為NewTest,包含測試用例,用來進行測試;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.AfterSuite;
import com.thunisoft.Employee.EmployeeDetail;
public class NewTest {
EmployeeLogic empBusinessLogic = new EmployeeLogic();
EmployeeDetail employee = new EmployeeDetail();
// test to check yearly salary
@Test
public void testCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);
double salary = empBusinessLogic
.calculateYearlySalary(employee);
Assert.assertEquals(96000, salary, 0.0, "8000");
}
}
NewTest.java類作用:測試員工年薪
4.測試執(zhí)行:選中這個類-》右鍵-》run as 選擇TestNG Test
5.查看執(zhí)行結(jié)果
控制臺會輸出如下:
可以看到,運行了一個test,成功輸出
TestNG輸出控制臺結(jié)果如下:
我們可以看到運行了一testCalculateYearlySalary測試方法,并且測試通過。
如果我們將測試代碼中的Assert.assertEquals(96000, salary, 0.0, "8000");改為
Assert.assertEquals(86000, salary, 0.0, "8000");,則運行結(jié)果如下: