Use Case:
Write a class and schedule it:
- The class should create a new Task (to review the opportunity) for each of the open Opportunity present in the org and assign it to the opportunity owner.
- Schedule the class to execute on every Monday at 9:00 AM.
// Implements the interface Schedulableglobal class OpportunityTasksCreation implements Schedulable {global void execute(SchedulableContext sc) {// Get the List of Open opportunitiesList<Opportunity> listOfOpportunities = [Select Id, OwnerIdFrom OpportunityWhere StageName != 'Closed Won' AND StageName != 'Closed Lost'];List<Task> tasks = new List<Task>();// Create a new task for each of the opportunityfor(Opportunity opp : listOfOpportunities) {tasks.add(new Task(OwnerId = opp.OwnerId,WhatId = opp.Id,Subject = 'Other',ActivityDate = System.today() + 5,Description = 'Review the Opportunity'));}insert tasks;}}
Test Class:
Test method to verify that Task should be created only for Open Opportunities and assigned to the owner of the opportunity.
@isTestprivate class OpportunityTasksCreationTest {@testSetupstatic void dataSetup() {Opportunity opp1 = new Opportunity(Name = 'Test Opp1', StageName = 'Prospecting', CloseDate = System.today() + 30);insert opp1;// Insert another opportunity with Stage as Closed WonOpportunity opp2 = new Opportunity(Name = 'Test Opp2', StageName = 'Closed Won', CloseDate = System.today() + 30);insert opp2;}// Test method to verify that Task should be created only for Open Opportunities// and assigned to the owner of the opportunity.@isTeststatic void testM() {// Schedule the job inside the start and stop test methodsTest.startTest();String cronExp = '0 0 9 ? * 2';String jobId = System.Schedule('OpportunityTasksCreation Schedule',cronExp,new OpportunityTasksCreation());Test.stopTest();// Assert that tasks should be created only for open opportunityOpportunity openOpp = [Select Id, OwnerId From Opportunity Where StageName != 'Closed Won'];// Get the created task and since there is only 1 open opportunity, so there should only be 1 taskList<Task> tasks = [Select Id, OwnerId, WhatId From Task];System.assertEquals(1, tasks.size(), 'Only 1 task should be present.');// Task should have the same whatId as the Open opportunity IdSystem.assertEquals(openOpp.Id, tasks[0].WhatId, 'Opportunity Id on Task does not match.');// Assert that owner for both task and open opportunity should be sameSystem.assertEquals(openOpp.OwnerId, tasks[0].OwnerId, 'Owner for both task and opportunity should be same.');}}
Code Coverage: 100%