Use Case:

Write a class and schedule it:

  1. 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.
  2. Schedule the class to execute on every Monday at 9:00 AM.
// Implements the interface Schedulable
global class OpportunityTasksCreation implements Schedulable {
global void execute(SchedulableContext sc) {
// Get the List of Open opportunities
List<Opportunity> listOfOpportunities = [Select Id, OwnerId
From Opportunity
Where StageName != 'Closed Won' AND StageName != 'Closed Lost'];
List<Task> tasks = new List<Task>();
// Create a new task for each of the opportunity
for(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.

@isTest
private class OpportunityTasksCreationTest {
@testSetup
static void dataSetup() {
Opportunity opp1 = new Opportunity(Name = 'Test Opp1', StageName = 'Prospecting', CloseDate = System.today() + 30);
insert opp1;
// Insert another opportunity with Stage as Closed Won
Opportunity 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.
    @isTest
static void testM() {
// Schedule the job inside the start and stop test methods
Test.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 opportunity
Opportunity 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 task
List<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 Id
System.assertEquals(openOpp.Id, tasks[0].WhatId, 'Opportunity Id on Task does not match.');
// Assert that owner for both task and open opportunity should be same
System.assertEquals(openOpp.OwnerId, tasks[0].OwnerId, 'Owner for both task and opportunity should be same.');
}
}
Code Coverage: 100%
Like it ? Share : Do Nothing

Leave a Reply