Generate report for all test classes in salesforce (SFDC)
/*
to meet this requirement i created a scheduler class (TestResultScheduler ), a main class (TestResultGenerator ) , and one future method class (testLog) to retrieve all test class status and email the result.
*/
// create scheduler class to call TestResultGenerator class
global class TestResultScheduler implements Schedulable
{
global void execute(SchedulableContext SC){
TestResultGenerator reportGenerator= new TestResultGenerator ();
reportGenerator.enqueueTests();
}
}
/*
to meet this requirement i created a scheduler class (TestResultScheduler ), a main class (TestResultGenerator ) , and one future method class (testLog) to retrieve all test class status and email the result.
*/
// create scheduler class to call TestResultGenerator class
global class TestResultScheduler implements Schedulable
{
global void execute(SchedulableContext SC){
TestResultGenerator reportGenerator= new TestResultGenerator ();
reportGenerator.enqueueTests();
}
}
--------------------------------------------------------------------------------------------------
/*
Test Result Generatorrr
*/
public class TestResultGenerator {
public ID myid;
// queue all test class
public void enqueueTests() {
String myString1 = '@IsTest';
Set<Id> testClasses = new Set<Id>();
DateTime d = datetime.now();
//SOSL to search all test classes
LIST<List<ApexClass>> testClasses1 = [FIND :myString1 IN ALL FIELDS RETURNING ApexClass];
System.debug('~~~~~~~~~~~~~~SOSL~~~~~~~~~~~ '+testClasses1);
//Add all test class id in testClasses
for(List<ApexClass> a: testClasses1)
{
for(ApexClass b : a ){
testClasses.add(b.id) ;
}
}
System.debug('~~~~~~~~~~~~~~SOSL Final testClasses~~~~~~~~~~~ '+testClasses);
//queue all test class
if(!testClasses.isEmpty())
{
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (Id cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls));
}
insert queueItems;
system.debug('~~~~~~~~~~~queueItems~~~ '+queueItems);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item = [SELECT ParentJobId,Status
FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
myid = item.parentjobid;
system.debug('~~~~~~~item~~~~ '+item);
Async_Apex_Job_Id__c jobid = new Async_Apex_Job_Id__c(Name=string.Valueof(d),AsyncApexJobId__c=myid);
insert jobid ;
if(myid != null){
checkClassStatus(myid);
checkMethodStatus(myid);
}
}
}
// Get the status and pass rate for each class
// whose tests were run by the job.
// that correspond to the specified job ID.
public void checkClassStatus(ID jobId) {
System.debug('~~~~~~~~jobIde '+jobId);
ApexTestQueueItem[] items = [SELECT ApexClass.Name, Status, ExtendedStatus
FROM ApexTestQueueItem
WHERE ParentJobId=:jobId];
for (ApexTestQueueItem item : items) {
String extStatus = item.extendedstatus == null ? '' : item.extendedStatus;
System.debug('~~~~~~~~item.ApexClass.Name '+item.ApexClass.Name + ':item.Status ' + item.Status + extStatus);
}
}
// Get the result for each test method that was executed.
public void checkMethodStatus(ID jobId) {
testLog.testResult(jobId); // Call future method
system.debug('~~~~~InSiDe checkMethodStatus method jobId '+jobId);
}
}
Test Result Generatorrr
*/
public class TestResultGenerator {
public ID myid;
// queue all test class
public void enqueueTests() {
String myString1 = '@IsTest';
Set<Id> testClasses = new Set<Id>();
DateTime d = datetime.now();
//SOSL to search all test classes
LIST<List<ApexClass>> testClasses1 = [FIND :myString1 IN ALL FIELDS RETURNING ApexClass];
System.debug('~~~~~~~~~~~~~~SOSL~~~~~~~~~~~ '+testClasses1);
//Add all test class id in testClasses
for(List<ApexClass> a: testClasses1)
{
for(ApexClass b : a ){
testClasses.add(b.id) ;
}
}
System.debug('~~~~~~~~~~~~~~SOSL Final testClasses~~~~~~~~~~~ '+testClasses);
//queue all test class
if(!testClasses.isEmpty())
{
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (Id cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls));
}
insert queueItems;
system.debug('~~~~~~~~~~~queueItems~~~ '+queueItems);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item = [SELECT ParentJobId,Status
FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
myid = item.parentjobid;
system.debug('~~~~~~~item~~~~ '+item);
Async_Apex_Job_Id__c jobid = new Async_Apex_Job_Id__c(Name=string.Valueof(d),AsyncApexJobId__c=myid);
insert jobid ;
if(myid != null){
checkClassStatus(myid);
checkMethodStatus(myid);
}
}
}
// Get the status and pass rate for each class
// whose tests were run by the job.
// that correspond to the specified job ID.
public void checkClassStatus(ID jobId) {
System.debug('~~~~~~~~jobIde '+jobId);
ApexTestQueueItem[] items = [SELECT ApexClass.Name, Status, ExtendedStatus
FROM ApexTestQueueItem
WHERE ParentJobId=:jobId];
for (ApexTestQueueItem item : items) {
String extStatus = item.extendedstatus == null ? '' : item.extendedStatus;
System.debug('~~~~~~~~item.ApexClass.Name '+item.ApexClass.Name + ':item.Status ' + item.Status + extStatus);
}
}
// Get the result for each test method that was executed.
public void checkMethodStatus(ID jobId) {
testLog.testResult(jobId); // Call future method
system.debug('~~~~~InSiDe checkMethodStatus method jobId '+jobId);
}
}
---------------------------------------------------------------------------------------------------------------
/*
result display and email the result
*/
public class testLog{ // calculate final data and email final result @future public static void testResult(ID jobId){ List<ApexTestResultInner> apxTstCstList = new List<ApexTestResultInner> (); List<ApexTestResult> apxTstRes = new List<ApexTestResult>(); system.debug('~~~~~future InSiDe checkMethodStatus method jobId '+jobId); // query on ApexTestResult object ApexTestResult[] results = [SELECT id,AsyncApexJobId,Outcome, ApexClass.Name, ApexClassId ,MethodName, Message, StackTrace FROM ApexTestResult WHERE AsyncApexJobId =: jobId]; for (ApexTestResult atr : results) { System.debug('~~~~~~future AsyncApexJobId '+atr.AsyncApexJobId+' ~~~~atr.ApexClass.Name '+atr.ApexClass.Name + ' .~~~ atr.MethodName~~ ' + atr.MethodName + '~~~:~~~atr.Outcome ' + atr.Outcome); ApexTestResultInner cust = new ApexTestResultInner(); cust.clsName=atr.ApexClass.Name; cust.ApexClassIdc = atr.ApexClassId ; cust.methodName =atr.MethodName ; cust.outCome=atr.Outcome; apxTstCstList.add(cust); if (atr.message != null) { System.debug('~~~~future atr.Message '+atr.Message + ' \n ~~~~at ' + atr.StackTrace); } } //create email contenets String emailContents = ''; emailContents = EmailContentsMethod(apxTstCstList); if(emailContents != null && emailContents != ''){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setHTMLBody(emailContents ); mail.setSenderDisplayName('AKG'); mail.setReplyTo('akg@mail.com'); //To List<String> l = new List<String>(); l.add('akg@email.com'); l.add('akg1@email.com'); mail.setToAddresses(l); //subject mail.setSubject('My report for test class'); Messaging.sendEmail( new Messaging.SingleEmailMEssage[]{ mail }); System.debug('Mail sent!!!*'); } } /* This method generates email contents */ public static string EmailContentsMethod(List<ApexTestResultInner> apxResList){ system.debug('~~~~~~future Inside EmailContents apxResList '+apxResList); // create HTML table structure for Email String emailData= ''; String space= ' '; String font = '<font face="calibri">'; String startTD = '<td style="border:0.1px dotted black;padding:0px;"> '; String endTD = '</td>'; String startTH = '<th style="border:0.1px solid;">'; String endTH = '</th>'; String startTR = '<tr>'; String endTR = '</tr>'; String startTable = '<table style="border:0.1px dotted black;padding:0px;">'; String endTable = '</table>'; // Email report value columns String ApexClass_Name = ''; String Method_Name = ''; String OutcomeRes = ''; try{ if(!apxResList.isEmpty()){ emailData = '<html><body><br>'; emailData += startTable + font; for(ApexTestResultInner t : apxResList){ ApexClass ac = new ApexClass(); ApexClass_Name = t.clsName; Method_Name = t.methodName ; OutcomeRes = t.outCome; // Table Header emailData += '<tr bgcolor="E3D8DA">'; emailData += startTH + 'Field' + endTH; emailData += startTH + 'Test class report' + endTH ; emailData += endTR; // ApexClass_Name emailData += startTR; emailData += startTD; emailData += 'Apex Class Name'; emailData += endTD; emailData += startTD; emailData += ApexClass_Name ; emailData += endTD; emailData += endTR; // Method_Name emailData += startTR; emailData += startTD; emailData += 'Method name'; emailData += endTD; emailData += startTD; emailData += Method_Name ; emailData += endTD; emailData += endTR; // Outcome Result emailData += startTR; emailData += startTD; emailData += 'Outcome'; emailData += endTD; emailData += startTD; emailData += OutcomeRes; emailData += endTD; emailData += endTR; } emailData += '</font></body></html>'; } } catch(Exception e){ System.debug('Inside Catch '+e); } return emailData; } // ApexTestResult inner custom object to display final result public class ApexTestResultInner{ public string clsName{get; set;} public string outCome{get; set;} public string methodName{get; set;} public Id ApexClassIdc {get; set;} } } |