TestNG测试
TestNG是一個(gè)受JUnit和NUnit啟發(fā)的測試框架
詳情參考https://testng.org/doc/
maven坐標(biāo)
<dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.0.0</version> </dependency> <!-- 測試報(bào)告樣式美化 --> <dependency><groupId>com.aventstack</groupId><artifactId>extentreports</artifactId><version>4.0.9</version> </dependency><dependency><groupId>com.vimalselvam</groupId><artifactId>testng-extentsreport</artifactId><version>1.3.1</version> </dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.3.5</version> </dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.2</version> </dependency>ExtentTestNGIReporterListener美化版報(bào)告監(jiān)聽器
import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import com.aventstack.extentreports.model.TestAttribute; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.configuration.ResourceCDN; import com.aventstack.extentreports.reporter.configuration.Theme; import org.testng.*; import org.testng.xml.XmlSuite;import java.io.File; import java.util.*;public class ExtentTestNGIReporterListener implements IReporter {//生成的路徑以及文件名private static final String OUTPUT_FOLDER = "report/";private static final String FILE_NAME = "index.html";private static final String REPORT_NAME = "user測試報(bào)告";private ExtentReports extent;@Overridepublic void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {init();boolean createSuiteNode = false;if(suites.size()>1){createSuiteNode=true;}for (ISuite suite : suites) {Map<String, ISuiteResult> result = suite.getResults();//如果suite里面沒有任何用例,直接跳過,不在報(bào)告里生成if(result.size()==0){continue;}//統(tǒng)計(jì)suite下的成功、失敗、跳過的總用例數(shù)int suiteFailSize=0;int suitePassSize=0;int suiteSkipSize=0;ExtentTest suiteTest=null;//存在多個(gè)suite的情況下,在報(bào)告中將同一個(gè)一個(gè)suite的測試結(jié)果歸為一類,創(chuàng)建一級(jí)節(jié)點(diǎn)。if(createSuiteNode){suiteTest = extent.createTest(suite.getName()).assignCategory(suite.getName());}boolean createSuiteResultNode = false;if(result.size()>1){createSuiteResultNode=true;}for (ISuiteResult r : result.values()) {ExtentTest resultNode;ITestContext context = r.getTestContext();if(createSuiteResultNode){//沒有創(chuàng)建suite的情況下,將在SuiteResult的創(chuàng)建為一級(jí)節(jié)點(diǎn),否則創(chuàng)建為suite的一個(gè)子節(jié)點(diǎn)。if( null == suiteTest){resultNode = extent.createTest(r.getTestContext().getName());}else{resultNode = suiteTest.createNode(r.getTestContext().getName());}}else{resultNode = suiteTest;}if(resultNode != null){resultNode.getModel().setName(suite.getName()+" : "+r.getTestContext().getName());if(resultNode.getModel().hasCategory()){resultNode.assignCategory(r.getTestContext().getName());}else{resultNode.assignCategory(suite.getName(),r.getTestContext().getName());}resultNode.getModel().setStartTime(r.getTestContext().getStartDate());resultNode.getModel().setEndTime(r.getTestContext().getEndDate());//統(tǒng)計(jì)SuiteResult下的數(shù)據(jù)int passSize = r.getTestContext().getPassedTests().size();int failSize = r.getTestContext().getFailedTests().size();int skipSize = r.getTestContext().getSkippedTests().size();suitePassSize += passSize;suiteFailSize += failSize;suiteSkipSize += skipSize;if(failSize>0){resultNode.getModel().setStatus(Status.FAIL);}resultNode.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",passSize,failSize,skipSize));}buildTestNodes(resultNode,context.getFailedTests(), Status.FAIL);buildTestNodes(resultNode,context.getSkippedTests(), Status.SKIP);buildTestNodes(resultNode,context.getPassedTests(), Status.PASS);}if(suiteTest!= null){suiteTest.getModel().setDescription(String.format("Pass: %s ; Fail: %s ; Skip: %s ;",suitePassSize,suiteFailSize,suiteSkipSize));if(suiteFailSize>0){suiteTest.getModel().setStatus(Status.FAIL);}}} // for (String s : Reporter.getOutput()) { // extent.setTestRunnerOutput(s); // }extent.flush();}private void init() {//文件夾不存在的話進(jìn)行創(chuàng)建File reportDir= new File(OUTPUT_FOLDER);if(!reportDir.exists()&& !reportDir .isDirectory()){reportDir.mkdir();}ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(OUTPUT_FOLDER + FILE_NAME);// 設(shè)置靜態(tài)文件的DNS//怎么樣解決cdn.rawgit.com訪問不了的情況htmlReporter.config().setResourceCDN(ResourceCDN.EXTENTREPORTS);htmlReporter.config().setDocumentTitle(REPORT_NAME);htmlReporter.config().setReportName(REPORT_NAME); // htmlReporter.config().setChartVisibilityOnOpen(true); // htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);htmlReporter.config().setTheme(Theme.STANDARD);htmlReporter.config().setCSS(".node.level-1 ul{ display:none;} .node.level-1.active ul{display:block;}");extent = new ExtentReports();extent.attachReporter(htmlReporter);extent.setReportUsesManualConfiguration(true);}private void buildTestNodes(ExtentTest extenttest, IResultMap tests, Status status) {//存在父節(jié)點(diǎn)時(shí),獲取父節(jié)點(diǎn)的標(biāo)簽String[] categories=new String[0];if(extenttest != null ){List<TestAttribute> categoryList = extenttest.getModel().getCategoryContext().getAll();categories = new String[categoryList.size()];for(int index=0;index<categoryList.size();index++){categories[index] = categoryList.get(index).getName();}}ExtentTest test;if (tests.size() > 0) {//調(diào)整用例排序,按時(shí)間排序Set<ITestResult> treeSet = new TreeSet<ITestResult>(new Comparator<ITestResult>() {@Overridepublic int compare(ITestResult o1, ITestResult o2) {return o1.getStartMillis()<o2.getStartMillis()?-1:1;}});treeSet.addAll(tests.getAllResults());for (ITestResult result : treeSet) {Object[] parameters = result.getParameters();String name="";//如果有參數(shù),則使用參數(shù)的toString組合代替報(bào)告中的namefor(Object param:parameters){name+=param.toString();}if(name.length()>0){if(name.length()>50){name= name.substring(0,49)+"...";}}else{name = result.getMethod().getMethodName();}if(extenttest==null){test = extent.createTest(name);}else{//作為子節(jié)點(diǎn)進(jìn)行創(chuàng)建時(shí),設(shè)置同父節(jié)點(diǎn)的標(biāo)簽一致,便于報(bào)告檢索。test = extenttest.createNode(name).assignCategory(categories);}//test.getModel().setDescription(description.toString());//test = extent.createTest(result.getMethod().getMethodName());for (String group : result.getMethod().getGroups())test.assignCategory(group);List<String> outputList = Reporter.getOutput(result);for(String output:outputList){//將用例的log輸出報(bào)告中test.debug(output);}if (result.getThrowable() != null) {test.log(status, result.getThrowable());}else {test.log(status, "Test " + status.toString().toLowerCase() + "ed");}test.getModel().setStartTime(getTime(result.getStartMillis()));test.getModel().setEndTime(getTime(result.getEndMillis()));}}}private Date getTime(long millis) {Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(millis);return calendar.getTime();} }UserTest.java
import com.example.pojo.User; import com.example.util.RestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.*; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.testng.annotations.DataProvider; import org.testng.annotations.Test;public class UserTest {private final static Logger log = LoggerFactory.getLogger(UserTest.class);@Test(dataProvider = "user")public void add(String userName, String passWord) throws InterruptedException {String url = "http://localhost/users/";MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();paramMap.add("userName",userName);paramMap.add("passWord",passWord);RestTemplate restTemplate = RestUtils.RestClient.getRestTemplate();String response = restTemplate.postForObject(url, paramMap, String.class);log.info("response:{}", response);}@Test(dataProvider = "userQuery")public void addJson(String userName, String passWord) {String url = "http://localhost/users";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);User user = new User();user.setUserName(userName);user.setPassWord(passWord);HttpEntity<User> entityParam = new HttpEntity<User>(user, headers);RestTemplate restTemplate = RestUtils.RestClient.getRestTemplate();String response = restTemplate.postForObject(url, entityParam, String.class);log.info("response:{}", response);}@Test(dataProvider = "userId")public void query(String id) {String uri = "http://localhost/users/{id}";RestTemplate restTemplate = RestUtils.RestClient.getRestTemplate();String response =restTemplate.getForObject(uri, String.class, id);log.info("response:{}", response);}@Test(dataProvider = "userId")public void queryEntiy(String id) {String uri = "http://localhost/users/{id}";RestTemplate restTemplate = RestUtils.RestClient.getRestTemplate();ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class, id);log.info("response:{}", response.getBody());}@Testpublic void queryAll() {String url = "http://localhost/users";RestTemplate restTemplate = RestUtils.RestClient.getRestTemplate();MultiValueMap paramMap = new LinkedMultiValueMap();HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(paramMap);ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);log.info("response:{}", exchange.getBody());}@DataProvider(name = "userId")public Object[] userId(){Object[] objects = new Object[]{"1","2"};return objects;}@DataProvider(name = "user")public Object[][] user(){Object[][] objects = new Object[][]{{"張三", "zhangsan"},{"李四", "lisi"}};return objects;}@DataProvider(name = "userQuery")public Object[][] userQuery(){Object[][] objects = new Object[][]{{"王五", "wangwu"}};return objects;}}testng.xml(測試模塊配置及ExtentReports報(bào)告監(jiān)聽配置)
<?xml version="1.0" encoding="UTF-8" ?><suite name="自動(dòng)測試報(bào)告"><test name="測試模塊"><classes><class name="com.example.user.UserTest" /></classes></test><listeners><listener class-name="com.example.listener.ExtentTestNGIReporterListener" /></listeners></suite>效果展示
總結(jié)
- 上一篇: Java开发的六大基本原则
- 下一篇: 如何测试朋友圈?这样回答会让HR眼前一亮