TestNG测试用例编写和执行

发表于:2017-2-09 10:41

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:菜鸟虫师    来源:51Testing软件测试网采编

  编写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");,则运行结果如下:
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号