Sunday, December 27, 2015

Self recurring class to create test records in Salesforse object

While working on Round Robin Incidents Assignment Routine for BMC Remedyforce we've built a tool to auto create test Incident records. This tool creates new record every one minute simulating real environment.

After minor modifications the same solution could be used for similar purposes to simulate creating records in standard or custom from SFDC UI. Below we provided example of self recurring class to create test Contact records.

The code has comments however please feel free to Contact Us if you have any questions.

APEX Class: AutoContactsCreator
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 12.2015
Description  : APEX class to automatically create new test Contact record (with some test data) each 5 minutes
History      :             
*/
global class AutoContactsCreator implements Schedulable{
 //Execute method
    global void execute(SchedulableContext SC) {
        //Code to check if test Account with name 'Test Account' exists and to create one if not.
        List acc = [SELECT id FROM Account WHERE Name = 'Test Account' limit 1];
        if(acc.size() == 0){
            Account NewAcc = new Account();
            NewAcc.Name = 'Test Account';
            insert NewAcc;
            acc.add(NewAcc);
        }
        //Code to check if test Contacts (created before with name AutoContact) exist and to identify the most recent Name (to auto increase name for new one).
        Contact con = new Contact();
        con.AccountId = acc[0].id;
        //Get next number of autocontact
            //Get last AutoContact record and parce LastName value
             List lastCon = [SELECT Name FROM Contact WHERE LastName LIKE 'AutoContact%' ORDER BY CreatedDate DESC LIMIT 1];
             //If exist, substring most recent name OR start form 1
             Integer NumOfNextAutoCon;
             if(lastCon.size() != 0){
                 String nameOfLastAutoCon = lastCon[0].Name;
                 NumOfNextAutoCon = Integer.valueOf(nameOfLastAutoCon.substringAfter('AutoContact')) + 1;
             }
             else{
                NumOfNextAutoCon = 1;
             }
        //Prepare values for First/Last Name, Phone, Email     
        con.FirstName = 'Test';
        con.LastName = 'AutoContact' + NumOfNextAutoCon;
            //Generate random number for phone from 1000000 to 9999999
            Integer uniqueVal =  Math.round(Math.random()*1000000) + 999999 ;
        con.Phone = '416' + uniqueVal;
        con.Email = 'AutoContact' + NumOfNextAutoCon + '@TestAccount.com';
        insert con;
        
        //This code section will schedule next class execution in 5 minutes from now
        datetime nextScheduleTime = system.now().addMinutes(1);
        string minute = string.valueof(nextScheduleTime.minute());
        string second = string.valueof(nextScheduleTime.second ());
        string cronvalue = second+' '+minute+' * * * ?';
        string jobName = 'AutoContactsCreator ' + nextScheduleTime.format('hh:mm');
        AutoContactsCreator p = new AutoContactsCreator();
        system.schedule(jobName, cronvalue , p);
 
        //This code section to be used to abort auto-scheduled job
        system.abortJob(sc.getTriggerId());
    }
    //Method to start shedule job form console
    public void startJob(){
        datetime nextScheduleTime = system.now().addMinutes(1);
        string minute = string.valueof(nextScheduleTime.minute());
        string second = string.valueof(nextScheduleTime.second ());
        string cronvalue = second+' '+minute+' * * * ?' ;
        string jobName = 'AutoContactsCreator ' + nextScheduleTime.format('hh:mm');   
        AutoContactsCreator p = new AutoContactsCreator();
        system.schedule(jobName, cronvalue , p);    
    }
    //Method to abort shedule job (with 'AutoContactsCreator' name) form console
    public void deleteJob(){
        CronTrigger job = [SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType FROM CronTrigger where CronJobDetail.Name LIKE 'AutoContactsCreator%'];
        system.abortJob(job.Id);
    }
 }

APEX Class: AutoContactsCreator_TESTclass
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 12.2015
Description  : APEX test coverage class for AutoContactsCreator class
History      :             
*/
@isTest
private class AutoContactsCreator_TESTclass {
    static testMethod void myUnitTest() {
        AutoContactsCreator autoCrCon = new AutoContactsCreator();
        autoCrCon.StartJob();
        autoCrCon.deleteJob();
        system.schedule('Test', '0 0 * * * ?' , autoCrCon);
    } 
}

SFDC Developer Console commands to use with AutoContactsCreator class

To execute self recurring class
AutoContactsCreator autoCrCon = new AutoContactsCreator();
autoCrCon.StartJob();

To abort self recurring class
AutoContactsCreator autoCrCon = new AutoContactsCreator();
autoCrCon.deleteJob();
Note: You also can abort the job manually here Setup -> Jobs -> Scheduled Jobs

Helpful command to DELETE all previously created by self recurring class test records
DELETE [SELECT id FROM Contact WHERE LastName LIKE 'AutoContact%'];