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
aressaress 

test class for batch use case

Need TEST CLASS for following batch scenario
USE CASE:
​A. Collection of Closed Won Opportunities 1. The Primary contact associated with an account needs to know which all are the closed won opportunities for his account per day. 2. Create a process which will run every day in the midnight & collect all the Closed won opportunities of that account in a day & send an email to Primary Contact. 3. The email body should contain the Opportunity Name & it's respective amount with the aggregated amount in the end.




---------------------------------------------------------BATCH CLASS----------------------------

global class ContactWithClosedWonOpportunities
implements Database.Batchable<sObject>, Database.Stateful {
/**
This Map will store the contact email IDs and respective List of Opportunites.
*/
Map<String,List<Opportunity>> contactOpprtunitiesMap =
new Map<String,List<Opportunity>>();
/**
This method will Query all Contacts associate with Account having Closed Won Opportunities.
@return Database.QueryLocator
*/
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(
'SELECT ' +
'Name, ' +
'( SELECT Email FROM Contacts WHERE Preferred_Contact__c = TRUE LIMIT 1 ), ' +
'( SELECT Name, Amount FROM Opportunities WHERE StageName LIKE \'Closed Won\') ' +
'FROM ' +
'Account ' +
'WHERE ' +
'id ' +
'IN ' +
'(SELECT AccountId FROM Contact WHERE Preferred_Contact__c = TRUE)'
);
}
/**
This method will add the values in contactOpportunitesMap.
@return Nothing.
*/
global void execute(Database.BatchableContext BC, List<sObject> scope) {
List<Account> accountList = (List<Account>) scope;
System.debug(scope + '------------------------- ');
for(Account accountRecord : accountList) {
if(accountRecord.Contacts[0].email != null) {
contactOpprtunitiesMap.put(
accountRecord.Contacts[0].email,
accountRecord.Opportunities
);
}
}
}
/**
This method will send to each primary contact with Opportunity name and Amount.
@return Nothing.
*/
global void finish(Database.BatchableContext BC) {
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
for( String mailId : contactOpprtunitiesMap.keySet() ) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> sendTo = new List<String>();
sendTo.add(mailId);
mail.setToAddresses(sendTo);
mail.setReplyTo('ayisha.sr@gmail.com');
mail.setSubject('All Closed Won Opportunities');
String body = '<html><body>Dear Sir/Mam, <br/><br/>';
body += 'All Closed Won Opportunities are - <br/>';
Decimal total = 0;
for( Opportunity opportunityRecord : contactOpprtunitiesMap.get(mailId) ) {
body += '&nbsp;&nbsp;&nbsp;&nbsp;' + opportunityRecord.Name + ': ' +
opportunityRecord.Amount + '<br/>';
total += opportunityRecord.Amount;
}
body += '<br/>&nbsp;&nbsp;&nbsp;&nbsp; <b>Total: ' + total + '</b></body></html>';
mail.setHtmlBody(body);
System.debug(body);
mails.add(mail);
}
Messaging.sendEmail(mails);
}
}

------------------------------------------------------------------SCHEDULER-------------------------------------------
global class ScheduleClosedWonOpportunities implements Schedulable {
/**
This method will execute RemoveDuplicateLeads Apex batch.
@return Nothing.
*/
global void execute(SchedulableContext sc) {
ContactWithClosedWonOpportunities batchObject = new ContactWithClosedWonOpportunities();
Database.executeBatch(batchObject);
}
}
Raj VakatiRaj Vakati
Use this code
 
@isTest

public class ContactWithClosedWonOpportunities_test {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
        List<Opportunity> opp = new List<Opportunity>();
        
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i, 
                                     billingcity='New York', billingcountry='USA'));
        }
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first', Preferred_Contact__c = true,email='testuser@gmail.com',
                                     lastname='last', accountId=account.id));
            opp.add( new Opportunity(Name='Test' , StageName ='Closed Won' , CloseDate =System.today() , Amount =100,AccountId = account.Id));
        }
        insert contacts;
    }
    
    static testmethod void test() {        
        System.Test.startTest();
        ContactWithClosedWonOpportunities uca = new ContactWithClosedWonOpportunities();
        Id batchId = Database.executeBatch(uca);
        System.Test.stopTest();
    }
}
 
@isTest
private class ScheduleClosedWonOpportunitiesTest {

    // Dummy CRON expression: midnight on March 15.
    // Because this is a test, job executes
    // immediately after Test.stopTest().
    public static String CRON_EXP = '0 0 0 15 3 ? 2022';

    static testmethod void testScheduledJob() {

        
        Test.startTest();
          String jobId = System.schedule('ScheduleClosedWonOpportunitiesTest',
            CRON_EXP, 
            new ScheduleClosedWonOpportunities ()); 
        Test.stopTest();
        
        

    }
}