function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AksharaAkshara 

test class for Apex Scheduler

Hello All,

Can someone help me write a test class for the below code.

Global class SendEmailToAccount implements Schedulable
{

   global void execute(SchedulableContext sc)
    {
                sendmail();
    }
 
    public void sendmail()
    {// Get default sender email address   
        OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress where DisplayName='Sender' limit 1];
      //Get Email Template
        EmailTemplate templateId = [Select id from EmailTemplate where name = 'TemplateName'];
        
       List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
       Set<Id> cid= new Set<id>();
       List<Account> accList = [select Id,primary_contact__c from Account where RecordType.developerName = 'My_Account_Record_Type'];
       List<Messaging.SendEmailResult> results;
       
       for(account acc:accList)
       {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTemplateID(templateId.Id); 
            mail.setSaveAsActivity(false);    
            mail.setTargetObjectId(acc.Primary_Contact__c);
            mail.setWhatId(acc.Id);
            mail.setOrgWideEmailAddressId(owa.id);
            allmsg.add(mail);
            
       }
     
        if(allmsg.size()>0)
        {
              
              results =  Messaging.sendEmail(allmsg,false);
         }
        if (!results.get(0).isSuccess()) 
        {
            
            System.StatusCode statusCode = results.get(0).getErrors()[0].getStatusCode();
            String errorMessage = results.get(0).getErrors()[0].getMessage();
            system.debug(errorMessage);
        }
     }                                     
}
Best Answer chosen by Akshara
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class.
 
@isTest
private class SendEmailToAccountTest 
{

	public static String CRON_EXP = '0 0 0 15 3 ? 2022';
	static testmethod void test() 
	{
		List<RecordType> listRT = [select id from Account where developerName = 'My_Account_Record_Type' limit 1 ];
		Account acc = new Account();
		acc.Name ='TEst';
		if(listRT.size() >0 )
		{
			acc.recordTypeid= listRT[0].id;
		}
		insert acc;

		Contact cont = new Contact();
		cont.LastName = 'TEst';
		cont.FirstName ='LastName';
		cont.email ='test@test.com';
		insert cont;

		acc.Primary_Contact__c = cont.id;
		update acc;	
		
		
		String jobId = System.schedule('SendEmailToAccount', CRON_EXP, new SendEmailToAccount ());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);

	}
}

Let us know if this will help you

 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try below test class.
 
@isTest
private class SendEmailToAccountTest 
{

	public static String CRON_EXP = '0 0 0 15 3 ? 2022';
	static testmethod void test() 
	{
		List<RecordType> listRT = [select id from Account where developerName = 'My_Account_Record_Type' limit 1 ];
		Account acc = new Account();
		acc.Name ='TEst';
		if(listRT.size() >0 )
		{
			acc.recordTypeid= listRT[0].id;
		}
		insert acc;

		Contact cont = new Contact();
		cont.LastName = 'TEst';
		cont.FirstName ='LastName';
		cont.email ='test@test.com';
		insert cont;

		acc.Primary_Contact__c = cont.id;
		update acc;	
		
		
		String jobId = System.schedule('SendEmailToAccount', CRON_EXP, new SendEmailToAccount ());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);

	}
}

Let us know if this will help you

 
This was selected as the best answer
AksharaAkshara
Hi Amit Chaudhary 8

Thanks for your response.I modified the below statement in the test class.However, it did not work as it did not return any rows.Do I need to use seeallData=true ?

 List<RecordType> listRT = [select id from RecordType where developerName = 'My_Account_Record_Type' limit 1 ];

@isTest
private class SendEmailToAccountTest 
{

    public static String CRON_EXP = '0 0 0 15 3 ? 2022';
    static testmethod void test() 
    {
        List<RecordType> listRT = [select id from RecordType where developerName = 'My_Account_Record_Type' limit 1 ];
        Account acc = new Account();
        acc.Name ='TEst';
        if(listRT.size() >0 )
        {
            acc.recordTypeid= listRT[0].id;
        }
        insert acc;

        Contact cont = new Contact();
        cont.LastName = 'TEst';
        cont.FirstName ='LastName';
        cont.email ='test@test.com';
        insert cont;

        acc.Primary_Contact__c = cont.id;
        update acc; 
        
        
        String jobId = System.schedule('SendEmailToAccount', CRON_EXP, new SendEmailToAccount ());
        CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        System.assertEquals(CRON_EXP, ct.CronExpression);

    }
}
Amit Chaudhary 8Amit Chaudhary 8
Below query should work without SeeAllDate= true
 
select id from RecordType where developerName = 'My_Account_Record_Type' limit 1

Please check your Account object Record Type and there Name and update same according to Developer Name
 
AksharaAkshara
Thanks Amit.You were right, it worked without SeeAllData=true.