Tùy chỉnh, PDF & Email TestNG Báo cáo trong Selenium webdriver
Trước khi chúng ta xem xét bất cứ điều gì khác, trước tiên chúng ta hãy hiểu –
Tại sao chúng ta cần báo cáo?
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ỉ là thực hiện Ứng dụng đang được thử nghiệm. Chúng tôi, với tư cách là người thử nghiệm 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. Ở đây báo cáo có tầm quan trọng đối với phần mềm Kiểm tra quá trình
TestNG Báo cáo
TestNG thư viện cung cấp một tính năng báo cáo rất tiện dụng. Sau khi thực hiện, Kiểm tra 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-
Index.html: Đây là báo cáo đầy đủ về quá trình thực thi hiện tại, chứa các thông tin như lỗi, nhóm, thời gian, nhật ký trình báo, tệp XML kiểm tra.
emailable-report.html: Đây là báo cáo tóm tắt về việc thực hiện kiểm thử hiện tại, trong đó có Trường hợp thử nghiệm thông báo màu xanh lục (đối với các trường hợp kiểm thử đạt) và màu đỏ (đối với các trường hợp kiểm thử thất bại).
Cách tùy chỉnh TestNG Report
TestNG báo cáo 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 ta có thể tùy chỉnh TestNG báo cáo
- 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à muốn nhận được 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 test case 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 có tên 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 nghe trong lớp Phương thức thử nghiệm.
Ví dụ về mã
RealGuru99TimeReport.java là lớp báo cáo theo 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ẽ trông giống như-
Giao diện IReporter
Nếu chúng tôi muốn tùy chỉnh báo cáo thử nghiệm cuối cùng được tạo bởi TestNG, chúng ta cần triển khai giao diện IReporter. Giao diện này chỉ có một phương thức để triển khai generateReport. Phương thức này có tất cả thông tin về việc thực hiện kiểm thử hoàn chỉnh trong Danh sách và chúng tôi có thể tạo báo cáo bằng cách sử dụng nó.
Ví dụ về mã
Guru99Reporter.java là file 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<XmlSuite> arg0, List<ISuite> 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<String,ISuiteResult> results = iSuite.getResults(); //Get the key of the result map Set<String> 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<ITestNGMethod> 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 demo 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ư-
PDF và Email của Báo cáo
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 tới ảnh chụp màn hình ở dạng 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 ta cần một Java API IText. Tải xuống đây . Có một lớp trình nghe tùy chỉnh khác thực sự đang triển khai jar IText này và tạo báo cáo pdf cho chúng tôi. Tải xuống đây
Hình trên hiển thị đị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 vấn đề này
Bước 1) Tạo lớp cơ sở
Bước 2) Tùy chỉnh JypersionListerner.Java (Mã tạo PDF)
Bước 3) Tạo TestGuru99PDFEmail.java để thực hiện các trường hợp thử nghiệm, tạo PDF
Bước 4) Thêm 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à Chụp ảnh màn hình
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ẽ giữ nguyên đị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 mã để hướng dẫn JypersionListener chụp ảnh màn hình khi Lỗi
- Đính kèm link ả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 để thực hiện các trường hợp thử nghiệm, tạo PDF
- Ở đây chúng ta sẽ thêm JyperionListener.class làm người nghe
- Chúng tôi sẽ thực hiện 3 trường hợp thử nghiệm.
- Sử dụng Assert.assertTrue chúng ta sẽ thất bại 2 trường hợp kiểm thử trong khi chỉ vượt qua một trường hợp.
- Ảnh chụp màn hình sẽ chỉ được chụp 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("http://google.com"); Assert.assertTrue(false); } //Testcase failed so screen shot generate @Test public void testPDFReporTwo(){ driver = BaseClass.getDriver(); driver.get("http:/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("https://demo.guru99.com"); Assert.assertTrue(true); }
Bước 4) Thêm 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 email báo cáo PDF
- Chúng tôi sẽ gửi email bằng Gmail
- Để bật Email, cần phải nhập nhiều tệp thư viện như mail.jar, pop3.jar, smptp.jar, v.v.
- Trước khi thực hiện, hãy nhập địa chỉ email từ, đến 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 dự án hoàn chỉnh tại đây
Lưu ý: Khi chúng ta nhấp vào liên kết ảnh chụp màn hình ở dạng 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.
Email được tạo ra sẽ trông như thế này
Tổng kết
- TestNG có khả năng báo cáo sẵn có trong đó.
- Sau khi thực hiện đầy đủ các trường hợp kiểm thử, TestNG tạo thư mục đầu ra thử nghiệm trong thư mục gốc của dự án.
- Trong thư mục test-output, có hai báo cáo chính là index.html và emailable-report.html.
- Để tùy chỉnh TestNG report chúng ta cần triển khai hai giao diện, ITestListener và IReporter.
- Nếu cần nhận báo cáo giữa quá trình thực thi, chúng ta cần ITestListener.
- Để tạo báo cáo cuối cùng sau khi thực hiện hoàn tất, chúng ta cần triển khai IReporter.
- Chụp ảnh màn hình, trong Selenium WebDriver, chúng ta cần gõ cast WebDriver vào giao diện TakesScreenShot.
- Để tạo báo cáo pdf, chúng tôi cần thêm jar IText vào dự án.
Tải về Selenium Tệp dự án cho bản demo trong hướng dẫn này