Khi chúng tôi đang sử dụng Selenium hoặc bất kỳ công cụ tự động hóa nào khác, chúng tôi đang thực hiện các thao tác trên ứng dụng web. Nhưng mục đích tự động hóa của chúng tôi không chỉ để thực hiện Ứng dụng đang thử nghiệm. Chúng tôi, với tư cách là người kiểm tra tự động hóa, có nhiệm vụ kiểm tra ứng dụng, tìm lỗi và báo cáo cho nhóm phát triển hoặc quản lý cấp cao hơn. Tại đây, báo cáo trở nên quan trọng đối với quy trình Kiểm tra phần mềm
Báo cáo TestNG
Thư viện TestNG cung cấp tính năng báo cáo rất tiện dụng. Sau khi thực hiện, Testng sẽ tạo thư mục đầu ra thử nghiệm ở thư mục gốc của dự án. Thư mục này chứa hai loại Báo cáo-
Mục lục. html. Đây là báo cáo đầy đủ về quá trình thực thi hiện tại chứa thông tin như lỗi, nhóm, thời gian, nhật ký trình báo cáo, tệp XML kiểm tra
emailable-báo cáo. html. Đây là báo cáo tóm tắt về quá trình thực hiện kiểm tra hiện tại, trong đó có thông báo Trường hợp kiểm tra có màu xanh lục [đối với trường hợp kiểm tra đạt] và màu đỏ [đối với trường hợp kiểm tra không thành công] được tô sáng
Cách tùy chỉnh Báo cáo TestNG
Báo cáo TestNG khá tiện dụng nhưng đôi khi chúng ta cần ít dữ liệu hơn trong báo cáo hoặc muốn hiển thị báo cáo ở một số định dạng khác như pdf, excel, v.v. hoặc muốn thay đổi bố cục của báo cáo
Có thể có hai cách chúng tôi có thể tùy chỉnh báo cáo TestNG
- Sử dụng giao diện ITestListener
- Sử dụng giao diện IReporter
Giao diện ITestListener
Chúng tôi sử dụng giao diện này khi cần tùy chỉnh báo cáo theo thời gian thực. Nói cách khác, nếu chúng ta đang thực thi một loạt các trường hợp thử nghiệm trong bộ TetNG và chúng ta muốn nhận báo cáo của từng trường hợp thử nghiệm, thì sau mỗi trường hợp thử nghiệm, chúng ta cần triển khai giao diện ITestListener. Giao diện này sẽ ghi đè phương thức onTestFailure, onTestStart, onTestSkipped để gửi trạng thái chính xác của trường hợp thử nghiệm hiện tại
Dưới đây là các bước chúng tôi sẽ làm theo
- Tạo một lớp nói RealGuru99Report và triển khai iTestListener trong đó
- Triển khai các phương thức của iTestListener
- Tạo phương thức thử nghiệm và thêm lớp RealGuru99Report làm trình lắng nghe trong lớp Phương thức thử nghiệm
Mã ví dụ
RealGuru99TimeReport. java là lớp báo cáo thời gian thực. Nó sẽ triển khai giao diện ITestListener để báo cáo
package testNGReport.realTimeReport; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; public class RealGuru99TimeReport implements ITestListener{ @Override public void onStart[ITestContext arg0] { System.out.println["Start Of Execution[TEST]->"+arg0.getName[]]; } @Override public void onTestStart[ITestResult arg0] { System.out.println["Test Started->"+arg0.getName[]]; } @Override public void onTestSuccess[ITestResult arg0] { System.out.println["Test Pass->"+arg0.getName[]]; } @Override public void onTestFailure[ITestResult arg0] { System.out.println["Test Failed->"+arg0.getName[]]; } @Override public void onTestSkipped[ITestResult arg0] { System.out.println["Test Skipped->"+arg0.getName[]]; } @Override public void onFinish[ITestContext arg0] { System.out.println["END Of Execution[TEST]->"+arg0.getName[]]; } @Override public void onTestFailedButWithinSuccessPercentage[ITestResult arg0] { // TODO Auto-generated method stub } }
TestGuru99RealReport. java là trường hợp thử nghiệm cho báo cáo thực
package testNGReport.realTimeReport; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners[RealGuru99TimeReport.class] public class TestGuru99RealReport { @Test public void testRealReportOne[]{ Assert.assertTrue[true]; } @Test public void testRealReportTwo[]{ Assert.assertTrue[false]; } //Test case depends on failed testcase= testRealReportTwo @Test[dependsOnMethods="testRealReportTwo"] public void testRealReportThree[]{ } }
Đầu ra sẽ giống như-
Giao diện IReporter
If we want to customize final test report generated by TestNG, we need to implement IReporter interface. This interface has only one method to implement generateReport. This method has all the information of a complete test execution in the List, and we can generate the report using it.
Mã ví dụ
Guru99Phóng viên. java là tệp được sử dụng để tùy chỉnh báo cáo
package testNGReport.iReporterReport; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.IReporter; import org.testng.IResultMap; import org.testng.ISuite; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.xml.XmlSuite; public class Guru99Reporter implements IReporter{ @Override public void generateReport[List arg0, List arg1, String outputDirectory] { // Second parameter of this method ISuite will contain all the suite executed. for [ISuite iSuite : arg1] { //Get a map of result of a single suite at a time Map results = iSuite.getResults[]; //Get the key of the result map Set keys = results.keySet[]; //Go to each map value one by one for [String key : keys] { //The Context object of current result ITestContext context = results.get[key].getTestContext[]; //Print Suite detail in Console System.out.println["Suite Name->"+context.getName[] + "::Report output Ditectory->"+context.getOutputDirectory[] +"::Suite Name->"+ context.getSuite[].getName[] +"::Start Date Time for execution->"+context.getStartDate[] +"::End Date Time for execution->"+context.getEndDate[]]; //Get Map for only failed test cases IResultMap resultMap = context.getFailedTests[]; //Get method detail of failed test cases Collection failedMethods = resultMap.getAllMethods[]; //Loop one by one in all failed methods System.out.println["--------FAILED TEST CASE---------"]; for [ITestNGMethod iTestNGMethod : failedMethods] { //Print failed test cases detail System.out.println["TESTCASE NAME->"+iTestNGMethod.getMethodName[] +"\nDescription->"+iTestNGMethod.getDescription[] +"\nPriority->"+iTestNGMethod.getPriority[] +"\n:Date->"+new Date[iTestNGMethod.getDate[]]]; } } } } }
TestGuru99ForReporter. java là bản trình diễn cho Báo cáo tùy chỉnh
package testNGReport.iReporterReport; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; //Add listener to listen report and write it when testcas finished @Listeners[value=Guru99Reporter.class] public class TestGuru99ForReporter { @Test[priority=0,description="testReporterOne"] public void testReporterOne[]{ //Pass test case Assert.assertTrue[true]; } @Test[priority=1,description="testReporterTwo"] public void testReporterTwo[]{ //Fail test case Assert.assertTrue[false]; } }
Đầu ra sẽ giống như-
Báo cáo PDF và Email
Việc triển khai báo cáo ở trên khá đơn giản và rõ ràng để giúp bạn bắt đầu tùy chỉnh báo cáo
Nhưng trong môi trường doanh nghiệp, bạn sẽ cần tạo các báo cáo có tính tùy chỉnh cao. Đây là kịch bản chúng ta sẽ giải quyết
- Tạo báo cáo tùy chỉnh ở dạng PDF
- CHỈ Chụp ảnh màn hình khi có lỗi. Liên kết đến ảnh chụp màn hình trong PDF
- Gửi email của PDF
Báo cáo PDF trông như thế này
Để tạo báo cáo pdf, chúng tôi cần có Java API IText. Tải về tại đây. Có một lớp trình nghe tùy chỉnh khác đang thực sự triển khai jar IText này và tạo báo cáo pdf cho chúng tôi. Tải về tại đây
Hình trên cho thấy định dạng mặc định của báo cáo PDF được tạo. Bạn có thể tùy chỉnh nó
Đây là cách chúng ta sẽ tiếp cận điều này
Bước 1] Tạo một lớp cơ sở
Bước 2] Tùy chỉnh JypersionListerner. Java [mã tạo PDF]
Bước 3] Tạo TestGuru99PDFEmail. java sẽ thực hiện các trường hợp thử nghiệm, tạo PDF
Bước 4] Nối mã vào TestGuru99PDFEmail. java để gửi báo cáo PDF qua email
Hãy xem xét các bước này
Bước 1] Tạo lớp cơ sở
Lớp cơ sở này có chức năng tạo WebDriver và Take Screenshot
package PDFEmail; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class BaseClass { static WebDriver driver; public static WebDriver getDriver[]{ if[driver==null]{ WebDriver driver ; System.setProperty["webdriver.gecko.driver","C:\\geckodriver.exe"]; driver = new FirefoxDriver[]; } return driver; } /** * This function will take screenshot * @param webdriver * @param fileWithPath * @throws Exception */ public static void takeSnapShot[WebDriver webdriver,String fileWithPath] throws Exception{ //Convert web driver object to TakeScreenshot TakesScreenshot scrShot =[[TakesScreenshot]webdriver]; //Call getScreenshotAs method to create image file File SrcFile=scrShot.getScreenshotAs[OutputType.FILE]; //Move image file to new destination File DestFile=new File[fileWithPath]; //Copy file at destination FileUtils.copyFile[SrcFile, DestFile]; } }
Bước 2] Tùy chỉnh JypersionListener. java
Chúng tôi sẽ gắn bó với định dạng báo cáo mặc định. Nhưng chúng tôi sẽ thực hiện 2 tùy chỉnh
- Thêm code hướng dẫn JypersionListener chụp màn hình khi Error
- Đính kèm liên kết của ảnh chụp màn hình trong báo cáo PDF
Thêm mã để đính kèm ảnh chụp màn hình vào báo cáo PDF
Bước 3] Tạo TestGuru99PDFEmail. java sẽ thực hiện các trường hợp thử nghiệm, tạo PDF
- Ở đây chúng tôi sẽ thêm JyperionListener. lớp như người nghe
- Chúng tôi sẽ thực hiện 3 trường hợp thử nghiệm
- Sử dụng khẳng định. assertTrue, chúng tôi sẽ thất bại 2 trường hợp thử nghiệm trong khi chỉ vượt qua một trường hợp
- Ảnh chụp màn hình sẽ chỉ được thực hiện cho các trường hợp thử nghiệm không thành công theo tùy chỉnh của chúng tôi
package PDFEmail; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterSuite; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import reporter.JyperionListener; //Add listener for pdf report generation @Listeners[JyperionListener.class] public class TestGuru99PDFReport extends BaseClass { WebDriver driver; //Testcase failed so screen shot generate @Test public void testPDFReportOne[]{ driver = BaseClass.getDriver[]; driver.get["//google.com"]; Assert.assertTrue[false]; } //Testcase failed so screen shot generate @Test public void testPDFReporTwo[]{ driver = BaseClass.getDriver[]; driver.get["/guru99.com"]; Assert.assertTrue[false]; } //Test test case will be pass, so no screen shot on it @Test public void testPDFReportThree[]{ driver = BaseClass.getDriver[]; driver.get["//demo.guru99.com"]; Assert.assertTrue[true]; }
Bước 4] Nối mã vào TestGuru99PDFEmail. java để gửi báo cáo PDF qua email
- Chúng tôi sẽ sử dụng chú thích @afterSuite để gửi báo cáo PDF qua email
- Chúng tôi sẽ gửi email bằng Gmail
- Để kích hoạt Email cần nhập nhiều file thư viện như mail. lọ, pop3. lọ, smtp. lọ, v.v.
- Trước khi bạn thực hiện điều này, hãy nhập từ, đến địa chỉ email và mật khẩu
//After complete execution send pdf report by email @AfterSuite public void tearDown[]{ sendPDFReportByGMail["FROM@gmail.com", "password", "TO@gmail.com", "PDF Report", ""]; } /** * Send email using java * @param from * @param pass * @param to * @param subject * @param body */ private static void sendPDFReportByGMail[String from, String pass, String to, String subject, String body] { Properties props = System.getProperties[]; String host = "smtp.gmail.com"; props.put["mail.smtp.starttls.enable", "true"]; props.put["mail.smtp.host", host]; props.put["mail.smtp.user", from]; props.put["mail.smtp.password", pass]; props.put["mail.smtp.port", "587"]; props.put["mail.smtp.auth", "true"]; Session session = Session.getDefaultInstance[props]; MimeMessage message = new MimeMessage[session]; try { //Set from address message.setFrom[new InternetAddress[from]]; message.addRecipient[Message.RecipientType.TO, new InternetAddress[to]]; //Set subject message.setSubject[subject]; message.setText[body]; BodyPart objMessageBodyPart = new MimeBodyPart[]; objMessageBodyPart.setText["Please Find The Attached Report File!"]; Multipart multipart = new MimeMultipart[]; multipart.addBodyPart[objMessageBodyPart]; objMessageBodyPart = new MimeBodyPart[]; //Set path to the pdf report file String filename = System.getProperty["user.dir"]+"\\Default test.pdf"; //Create data source to attach the file in mail DataSource source = new FileDataSource[filename]; objMessageBodyPart.setDataHandler[new DataHandler[source]]; objMessageBodyPart.setFileName[filename]; multipart.addBodyPart[objMessageBodyPart]; message.setContent[multipart]; Transport transport = session.getTransport["smtp"]; transport.connect[host, from, pass]; transport.sendMessage[message, message.getAllRecipients[]]; transport.close[]; } catch [AddressException ae] { ae.printStackTrace[]; } catch [MessagingException me] { me.printStackTrace[]; } } }
Tải về toàn bộ dự án tại đây
Ghi chú. Khi chúng tôi nhấp vào liên kết ảnh chụp màn hình trong pdf, nó sẽ hiển thị hộp thoại bảo mật. Chúng tôi phải cho phép hộp thoại này mở pdf