编写TestNG用例测试基本上包括以下步骤:
编写业务逻辑
针对业务逻辑中涉及的方法编写测试类,在代码中插入TestNG的注解
直接执行测试类或者添加一个testng.xml文件
运行 TestNG.
下面我们介绍一个完整的例子来测试一个逻辑类;
1.创建一个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.创建一个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.创建一个测试类,为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.测试执行:选中这个类-》右键-》run as 选择TestNG Test
5.查看执行结果
控制台会输出如下:
可以看到,运行了一个test,成功输出
TestNG输出控制台结果如下:
我们可以看到运行了一testCalculateYearlySalary测试方法,并且测试通过。
如果我们将测试代码中的Assert.assertEquals(96000, salary, 0.0, "8000");改为
Assert.assertEquals(86000, salary, 0.0, "8000");,则运行结果如下:
手机扫一扫
移动阅读更方便
你可能感兴趣的文章