Wednesday, May 23, 2012

Using TestListenerAdapter Class

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class TestReporter extends TestListenerAdapter{
    File f;
    BufferedWriter bw;

    public void onStart(ITestContext testContext){
        System.out.println("ON START");
         f = new File("c:\\source.html");
         try{
             bw = new BufferedWriter(new FileWriter(f));
         }
         catch(Exception e){

         }
    }

    public void onFinish(ITestContext testContext){
        System.out.println("ON Finish");
         try{
             bw.close();
         }
         catch(Exception e){

         }
    }

    public void onTestFailure(ITestResult arg0) {
    System.out.println("Failed Test: "+arg0.getName()+" Reason:"+arg0.getThrowable()+" Class : "+arg0.getTestClass().getName());

     try{
         writeToFile(arg0.getName(), arg0.getThrowable().toString(), arg0.getTestClass().getName(), "red", "Failed");
     }
     catch(Exception e){
     }
    }

    public void onTestSkipped(ITestResult arg0) {
    System.out.println("Skipped test: "+arg0.getName()+" Reason"+arg0.getThrowable()+" Class : "+arg0.getTestClass().getName());
        System.out.println("Test skipped");

         try{
             writeToFile(arg0.getName(), arg0.getThrowable().toString(), arg0.getTestClass().getName(), "yellow", "Skipped");
         }
         catch(Exception e){
         }
    }

    public void onTestSuccess(ITestResult arg0) {
        System.out.println("Passed Test: "+arg0.getName());
    }

    public void writeToFile(String testName, String throwable, String className, String color, String status) throws IOException{
         bw.write("<tr><td style=\"background-color:" + color + ";\">" + status + "</td><td>" + className + "</td><td>" + testName + "</td><td>" + throwable + "</td></tr>");
         bw.newLine();
    }
}

No comments:

Post a Comment