编写TestNG用例测试基本上包括以下步骤:
编写业务逻辑
针对业务逻辑中涉及的方法编写测试类,在代码中插入TestNG的注解
直接执行测试类或者添加一个testng.xml文件
运行 TestNG.
下面我们介绍一个完整的例子来测试一个逻辑类;
1.创建一个pojo类EmployeeDetail.java
public classEmployeeDetail {privateString name;private doublemonthlySalary;private intage;/***@returnthe name*/
publicString getName() {returnname;
}/***@paramname the name to set*/
public voidsetName(String name) {this.name =name;
}/***@returnthe monthlySalary*/
public doublegetMonthlySalary() {returnmonthlySalary;
}/***@parammonthlySalary the monthlySalary to set*/
public void setMonthlySalary(doublemonthlySalary) {this.monthlySalary =monthlySalary;
}/***@returnthe age*/
public intgetAge() {returnage;
}/***@paramage the age to set*/
public void setAge(intage) {this.age =age;
}
}
EmployeeDetail用来:
get/set 员工的名字的值
get/set 员工月薪的值
get/set员工年龄的值
2.创建一个EmployeeLogic.java
public classEmployeeLogic {//Calculate the yearly salary of employee
public doublecalculateYearlySalary(EmployeeDetail employeeDetails){double yearlySalary=0;
yearlySalary= employeeDetails.getMonthlySalary() * 12;returnyearlySalary;
}
}
EmployeeLogic.java用来:
计算员工年工资
3.创建一个测试类,为NewTest,包含测试用例,用来进行测试;
importorg.testng.Assert;importorg.testng.annotations.Test;importorg.testng.annotations.BeforeMethod;importorg.testng.annotations.AfterMethod;importorg.testng.annotations.DataProvider;importorg.testng.annotations.BeforeClass;importorg.testng.annotations.AfterClass;importorg.testng.annotations.BeforeTest;importorg.testng.annotations.AfterTest;importorg.testng.annotations.BeforeSuite;importorg.testng.annotations.AfterSuite;importcom.thunisoft.Employee.EmployeeDetail;public classNewTest {
EmployeeLogic empBusinessLogic= newEmployeeLogic();
EmployeeDetail employee= newEmployeeDetail();//test to check yearly salary
@Testpublic voidtestCalculateYearlySalary() {
employee.setName("Rajeev");
employee.setAge(25);
employee.setMonthlySalary(8000);double salary =empBusinessLogic
.calculateYearlySalary(employee);
Assert.assertEquals(96000, salary, 0.0, "8000");
}
}
NewTest.java类作用:测试员工年薪
4.测试执行:选中这个类-》右键-》run as 选择TestNG Test
5.查看执行结果
控制台会输出如下:
可以看到,运行了一个test,成功输出
TestNG输出控制台结果如下:
我们可以看到运行了一testCalculateYearlySalary测试方法,并且测试通过。
如果我们将测试代码中的Assert.assertEquals(96000, salary, 0.0, "8000");改为
Assert.assertEquals(86000, salary, 0.0, "8000");,则运行结果如下: