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
Jasjeet GrewalJasjeet Grewal 

Test class for Schedulable Apex class

Hi,

I have a schedulable apex class that executes method AddRecords.
Method create a new record for object User_Tasks__c for each user account in org. One of the field User_Tasks__c.Total_tasks__c is filled with total tasks count of the user.

I am struggling to write a test class for it.
Sharing code for apex class and test class.
 
global class CreateUserTasks Implements Schedulable{
    global void execute(SchedulableContext sc){
            AddRecords();
    }
    
    public static void AddRecords(){
        List<User> users = [select id,Name from User where IsActive=true];
        Map<Id, Integer> taskCounts = new Map<Id, Integer>();
        List<AggregateResult> ars;
        List<User_Task__c> userTasks= New List<User_Task__c>();
    
        ars = [SELECT  OwnerID owner, count(ID) taskCount FROM Task WHERE OwnerId in (select id from User where IsActive=true) and isClosed = false group by OwnerId];
        
        for(AggregateResult ar : ars) {
            taskCounts.put((ID)ar.get('owner'), Integer.valueOf(ar.get('taskCount')));
            User_Task__c usertask = New User_Task__c();
            usertask.tasks_completed__c = 0;
            usertask.Date__c = System.today();
            usertask.Total_tasks__c = Integer.valueOf(ar.get('taskCount'));
            
        }
        insert userTasks;
        }
}

My test class has 0% test coverage. My test class:
@isTest
private class TestCreateUserTasks{
	static testMethod void validateSampleApex() {
        
		Test.startTest();
        
        User u1 = new user();
        u1.LastName = 'A';
        u1.Email = 'test@test.com';
        u1.Alias = 'A';
        u1.Username = 'A1234444@test.com';
        u1.CommunityNickname = 'A12';
        u1.LocaleSidKey = 'en_US';
        u1.TimeZoneSidKey = 'GMT';
        u1.ProfileID = '00e1C000001J8DbQAK';
        u1.LanguageLocaleKey = 'en_US';
        u1.EmailEncodingKey = 'UTF-8';
        insert u1;
        
        User_Task__c utA = New User_Task__c();
        utA.Date__C = System.today();
        utA.Total_tasks__c = 0;      
        insert utA;
        
        List<Task> tasks = new List<Task>{};

        System.runAs(u1) {
        	Task tA = new Task(Subject='TestA1',Status='New',Priority='Normal',CallType='Outbound');
            insert tA; 
        }
        
        List<User> users = [select id,Name from User where IsActive=true];

        List<User_Task__c> utList= [Select ID From User_Task__c where date__c = :System.today()];
        		
        System.assertEquals(2, utList.size());
        
		Test.stopTest();     
	}
}

Can someone please help me how to test schedulable class with method to insert new records.

Thanks,
Jas
Best Answer chosen by Jasjeet Grewal
Maharajan CMaharajan C
Hi Jas,

Try the below test class:
 
@isTest
private class TestCreateUserTasks{
	
	@testSetup static void setup() {

		Profile pf= [Select Id from profile where Name='System Administrator'];
		
		User u1 = new user();
		u1.LastName = 'A';
		u1.Email = 'test@test.com';
		u1.Alias = 'A';
		u1.Username = 'A1234444@test.com';
		u1.CommunityNickname = 'A12';
		u1.LocaleSidKey = 'en_US';
		u1.TimeZoneSidKey = 'GMT';
		u1.ProfileID = pf.Id;
		u1.LanguageLocaleKey = 'en_US';
		u1.EmailEncodingKey = 'UTF-8';
		insert u1;
		
		// Add if there is any other mandatory fields are there to create account.
		Account acc = new Account(Name = 'Test Account');
		insert acc;
		
		List<Task> tasks = new List<Task>{};

		for(integer i = 0; i < 5 ; i++) {
			Task tA = new Task(Subject='TestA' + i ,Status='New',Priority='Normal',CallType='Outbound', OwnerId = u1.Id, WhatId = acc.Id;);
			tasks.add(tA); 
		}
		
		if(!tasks.IsEmpty())
			insert tasks;
		
	}
	
	static testMethod void validateSampleApex() {
	
		Test.startTest();
		
		String CRON_EXP = '0 6 * * * ?';
		String jobId = System.schedule('Count Tasks',  CRON_EXP, new CreateUserTasks());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);
			
		Test.stopTest();         
		    
	}
	
	static testMethod void validateSampleApex1() {
	
		Test.startTest();
		
		CreateUserTasks.AddRecords();
			
		Test.stopTest();     
		
		List<User_Task__c> utList= [Select ID From User_Task__c];
		System.assert(utList.size() > 0);		
		    
	}
}

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Jas,

Try the below test class:
 
@isTest
private class TestCreateUserTasks{
	
	@testSetup static void setup() {

		Profile pf= [Select Id from profile where Name='System Administrator'];
		
		User u1 = new user();
		u1.LastName = 'A';
		u1.Email = 'test@test.com';
		u1.Alias = 'A';
		u1.Username = 'A1234444@test.com';
		u1.CommunityNickname = 'A12';
		u1.LocaleSidKey = 'en_US';
		u1.TimeZoneSidKey = 'GMT';
		u1.ProfileID = pf.Id;
		u1.LanguageLocaleKey = 'en_US';
		u1.EmailEncodingKey = 'UTF-8';
		insert u1;
		
		// Add if there is any other mandatory fields are there to create account.
		Account acc = new Account(Name = 'Test Account');
		insert acc;
		
		List<Task> tasks = new List<Task>{};

		for(integer i = 0; i < 5 ; i++) {
			Task tA = new Task(Subject='TestA' + i ,Status='New',Priority='Normal',CallType='Outbound', OwnerId = u1.Id, WhatId = acc.Id;);
			tasks.add(tA); 
		}
		
		if(!tasks.IsEmpty())
			insert tasks;
		
	}
	
	static testMethod void validateSampleApex() {
	
		Test.startTest();
		
		String CRON_EXP = '0 6 * * * ?';
		String jobId = System.schedule('Count Tasks',  CRON_EXP, new CreateUserTasks());
		CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
		System.assertEquals(CRON_EXP, ct.CronExpression);
			
		Test.stopTest();         
		    
	}
	
	static testMethod void validateSampleApex1() {
	
		Test.startTest();
		
		CreateUserTasks.AddRecords();
			
		Test.stopTest();     
		
		List<User_Task__c> utList= [Select ID From User_Task__c];
		System.assert(utList.size() > 0);		
		    
	}
}

Thanks,
Maharajan.C
This was selected as the best answer
Jasjeet GrewalJasjeet Grewal
Thanks maharajan for help.

String CRON_EXP = '0 6 * * *
This expression means the time scheduled for test?

If yes, please tell me what time it states that job should be scheduled at?

Thanks,
Jas