TestNG-测试框架+case监听

本文介绍了一个基于Selenium WebDriver和TestNG的自动化测试框架实现案例。该框架使用Java编程语言,通过集成TestNG实现了测试用例的组织与执行,并利用自定义监听器来捕获测试过程中的失败情况并截图保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

package HelloMaven.HelloMaven;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;

public class BaseDriver {
	public WebDriver driver;
	
	
	public WebDriver GetDriver() {
		return driver;
	}
	
	@BeforeClass 
	public void testbeforeclass(){
		System.out.println("before class---- called");
		selectDriver select = new selectDriver();
		driver = select.DriverSelect("Chrome");
		driver.manage().window().maximize();
	}
	
	@BeforeMethod
	public void testbeforemethod() {
		System.out.println("before method ------ called");

	}
	
	@AfterClass
	public void testafterclass() {
		System.out.println("after class ------ called");
		driver.close();
	}
	
	@AfterMethod
	public void testaftermethod() {
		System.out.println("after method ------- called");
		//driver.close();
	}
}

在test case中的应用

package HelloMaven.HelloMaven;

import org.openqa.selenium.By;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

@Listeners({TestNgListener.class})
public class testNG_test extends BaseDriver{

	

	@Test
	public void test1() {
		System.out.println("test --------> test1 called");
		//Assert.assertEquals(1, 2);
		driver.get("http://www.imooc.com");
	}
	
	@Test
	public void test2() {
		System.out.println("test --------> test2 called");
		driver.get("http://www.imooc.com");
		driver.findElement(By.className("user"));
	}
}

对test case进行监听

package HelloMaven.HelloMaven;


import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class TestNgListener extends TestListenerAdapter{
	
	@Override
	public void onTestFailure(ITestResult tr) {
		System.out.println("on test failure");
		BaseDriver base = (BaseDriver)tr.getInstance();
		WebDriver driver = base.GetDriver();
		ScreenShot(driver);
		super.onTestFailure(tr);
		
	}
	
	@Override
	public void onTestSuccess(ITestResult tr) {
		System.out.println("on test success");
		super.onTestSuccess(tr);
	}
	
	@Override
	public void onTestSkipped(ITestResult tr) {
		System.out.println("on test skipped");
		super.onTestSkipped(tr);
	}
	
	public void ScreenShot(WebDriver driver) {
		long curdate = System.currentTimeMillis();
		String path = String.valueOf(curdate) + ".png";
		String curpath = System.getProperty("user.dir");
		System.out.println(curpath);
		path = curpath + "/" + path;
		File Screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
		try {
			FileUtils.copyFile(Screen, new File(path));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

### Java TestNG HttpClient Allure Fastjson JSONPath POI YAML Log4 Integration Best Practices #### 使用TestNG进行测试管理 TestNG 是一种强大的测试框架,用于编写和运行单元测试、集成测试和其他类型的测试。`testng.xml` 文件定义了测试套件的结构,包括测试集 (`<test>`) 和测试类集合 (`<classes>`)[^2]。通过 `testng.xml` 可以灵活地控制测试执行顺序、依赖关系以及其他参数。 #### 集成HttpClient实现API调用 HttpClient 提供了一种简单而高效的方式来发送HTTP请求并处理响应。它支持多种HTTP方法 (如 GET, POST, PUT 等),并且能够轻松处理HTTPS协议[^4]。在自动化测试中,通常会结合TestNG来验证API的功能性和性能指标。 以下是使用HttpClient发起POST请求的一个示例: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class ApiClient { public CloseableHttpResponse postRequest(String url, String payload) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost request = new HttpPost(url); StringEntity entity = new StringEntity(payload, "UTF-8"); request.setEntity(entity); request.setHeader("Content-Type", "application/json"); return httpClient.execute(request); } } } ``` #### 利用Allure生成美观的测试报告 Allure 是一款流行的开源工具,专门用来生成详细的HTML格式测试报告。它可以与TestNG无缝集成,提供丰富的图表展示测试结果,并允许附加截图或其他证据到失败案例中[^5]。为了启用Allure监听器,在pom.xml文件里需引入相应的插件: ```xml <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M7</version> <configuration> <suiteXmlFiles> <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile> </suiteXmlFiles> </configuration> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>io.qameta.allure</groupId> <artifactId>allure-maven</artifactId> <version>2.12.0</version> </plugin> </plugins> </reporting> ``` #### 数据解析库的选择——FastJson vs JsonPath 当涉及到复杂的JSON对象操作时,可以选择不同的库来进行序列化/反序列化或者提取特定字段值的任务。FastJson因其高性能表现成为许多开发者首选方案之一;然而对于只需要读取部分节点的情况,则可能更倾向于轻量级解决方案比如JsonPath[^5]。 下面展示了如何利用这两个库分别完成相同目标的例子: ##### 使用FastJson转换Java Bean至JSON字符串 ```java import com.alibaba.fastjson.JSON; public class ExampleWithFastJson { public static void main(String[] args){ User user=new User(); user.setName("John Doe"); System.out.println(JSON.toJSONString(user)); } static class User{ private String name; // Getter Setter omitted for brevity. } } ``` ##### 应用JsonPath查询嵌套属性 ```java import com.jayway.jsonpath.JsonPath; public class ExampleWithJsonPath { public static void main(String[] args)throws Exception{ Object document=JsonPath.parse("{\"store\":{\"book\":[{\"author\":\"Nigel Rees\"}]}}").read("$.store.book[0].author"); System.out.println(document); // Output: Nigel Rees } } ``` #### Excel/PDF文档处理借助Apache POI Library 如果项目需求涉及Excel表格的操作或者是PDF文件生成等功能的话,那么可以考虑采用Apache POI library作为技术支持[^5]。此库提供了全面的支持去创建、修改Microsoft Office格式的数据源。 这里给出一段简单的代码片段说明怎样加载现有的XLSX工作簿并将其中的内容打印出来: ```java import org.apache.poi.ss.usermodel.*; import java.io.File; import java.io.FileInputStream; public class ReadExcelExample { public static void main(String[] args) throws Exception { FileInputStream fileInputStream = new FileInputStream(new File("/path/to/excel/file.xlsx")); Workbook workbook = WorkbookFactory.create(fileInputStream); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while(rowIterator.hasNext()){ Row currentRow=rowIterator.next(); Iterator<Cell> cellIterator=currentRow.cellIterator(); while(cellIterator.hasNext()){ Cell currentCell=cellIterator.next(); switch(currentCell.getCellType()){ case STRING -> System.out.print(currentCell.getStringCellValue()+" "); case NUMERIC->System.out.print(currentCell.getNumericCellValue()+" "); default -> {} } } System.out.println(""); } workbook.close(); } } ``` #### 日志记录推荐Log4j Framework 最后但同样重要的是设置良好的日志机制以便于后续分析问题所在位置及时刻追踪程序流程走向。Log4J以其灵活性著称,允许自定义不同级别消息输出渠道以及样式布局[^5]。 配置log4j.properties如下所示即可满足基本应用场景下的要求: ```properties # Root logger option log4j.rootLogger=DEBUG, stdout, file # Direct log messages to console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n # Direct log messages to a log file log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./logs/app.log log4j.appender.file.MaxFileSize=10MB log4j.appender.file.MaxBackupIndex=10 log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值