• Arpitha Gowda
  • NEWBIE
  • 10 Points
  • Member since 2017
  • Salesforce Developer
  • DhruvaSoft technologies

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 5
    Replies
Hello all

I have Designed a batch apex where it gets automatically approved after 24Hrs if no actions are taken, and i have 
written test class which is getting covered only 15%, how do increase the code coverage, Please help
 
global class BatchOpportunityApproval implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String Query = 'SELECT Id,DaysSinceApprovalNotDone__c,Approval_Sent_Date_Time__c FROM Opportunity where DaysSinceApprovalNotDone__c = 1 AND Approval_Sent_Date_Time__c !=null';
        return Database.getQueryLocator(Query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope){

        List<Opportunity> opplist = new List<Opportunity>();
        Set<Id> OppIds = New Set<Id>();
        for(Opportunity opp : scope){    
            opp.Approval_Sent_Date_Time__c = null;
            opplist.add(opp);
            OppIds.add(opp.id);
        }
        
        Set<Id> pIds = (new Map<Id, ProcessInstance>([SELECT Id,Status,TargetObjectId FROM ProcessInstance where Status='Pending' and TargetObjectId IN :OppIds])).keySet();
        Set<Id> pwi = (new Map<Id, ProcessInstanceWorkitem>([SELECT Id,ProcessInstanceId FROM ProcessInstanceWorkitem WHERE ProcessInstanceId IN :pIds])).keySet();
        List<Approval.ProcessWorkitemRequest> allReq = new List<Approval.ProcessWorkitemRequest>(); 
        if(!pwi.IsEmpty()){
            for (Id pInstanceWorkitemsId:pwi){
                system.debug(pInstanceWorkitemsId);
                Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
                req.setComments('24hrs Auto Approval for Pending Opportunities');
                req.setAction('Approve');
                req.setWorkitemId(pInstanceWorkitemsId);
                system.debug(pInstanceWorkitemsId);
                allReq.add(req);
            }
        }
        
        if(allReq.size()>0){
            Approval.ProcessResult[] result2 =  Approval.process(allReq);
        }     
        
        if(opplist.size()>0){
            Database.update(opplist,false);
        }
    }
    
    global void finish(Database.BatchableContext BC) {}
    
    global void execute(SchedulableContext sc) {}
}

My test class covering only 15%
 
@isTest
public class BatchOpportunityApprovalTestclass {
    static testMethod void mytestmethod(){
        Test.startTest();
        Account ac = new Account(Name='TestAccount', Website='www.salesforce.com');
        insert ac;
        
        List<Opportunity> opps = new List<Opportunity>();
        for(Integer k=0; k<50; k++){
            opps.add(new Opportunity(Name=ac.Name + ' Opportunity ' + k,
                                     StageName='Stage 0 (0%)',
                                     CloseDate=System.today(),
                                     Practices__c = 'Cloud',
                                     Status__c = 'Active',
                                     No_of_Engineers__c = 20,
                                     Competition_Fulfilment_LOSS__c = 20,
                                     Priority__c = '1 - Lowest',
                                     Sales_Action_Items_Remarks__c = 'Hello',
                                     Category__c = 'Critical',
                                     Fulfilled_as_on_date_WIN__c = 20,
                                     Customer_Kept_On_Hold_Fulfilled__c = 20,
                                     Duration_Months__c = 10,
                                     Business_Model__c = 'T&M',
                                     Customer_Location__c = 'Bangalore',
                                     Revenue_Type__c = 'EE-Existing Customer Existing Business',
                                     Experience_Range__c = 'Min Exp',
                                     Skill_Category__c = 'Development',
                                     EnggStatusType__c = 'self',
                                     RMG_Remarks__c = 'HelloWorld',
                                     //Approval_Sent_Date_Time__c = system.now()-1,                                     
                                     AccountId=ac.Id));
        }
        insert opps;
        
        Approval.ProcessSubmitRequest [] requestList = new Approval.ProcessSubmitRequest []{};
        for(Opportunity op: [SELECT Id, Name,DaysSinceApprovalNotDone__c, Approval_Sent_Date_Time__c FROM Opportunity WHERE Id IN: opps]){
            System.debug('op>>>>'+op.Approval_Sent_Date_Time__c);
            System.debug('op>>>><<<<'+op.DaysSinceApprovalNotDone__c);
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();          
            req.setComments('Submitting approval request');        
            req.setObjectId(op.id);
            req.setProcessDefinitionNameOrId('Opportunity Approval Process');
            requestList.add(req);
           
        }
        if(requestList.size()>0){
            Approval.ProcessResult[] result = Approval.process(requestList);
        }
            
        SchedularForBatchOpportunityApproval testsche = new SchedularForBatchOpportunityApproval();
        String sch = '0 0 1 * * ?';
        system.schedule('Test status Check', sch, testsche );
        
        Test.stopTest();
    }
    
     public static testMethod void testschedule() {
        Test.StartTest();
        SchedularForBatchOpportunityApproval sh1 = new SchedularForBatchOpportunityApproval();
        String sch = '0 00 01 * * ?'; 
        //ID batchprocessid = Database.executeBatch(sh1);
        String jobId = system.schedule('SchedularForBatchOpportunityApproval', sch, sh1);
        System.assert(jobId != null);
        Test.stopTest(); 
    }
}

​​​​​​​
Hello All

How do i write test class for below Batch apex class, 
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c FROM Lead where No_Enquiry_Email_Sent__c=false AND Status=\'Enquiry\' And (CreatedDate = YESTERDAY OR LastModifiedDate = YESTERDAY) limit 1';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
                // Step 2: Set list of people who should get the email
                String[] toAddresses = new String[] {prod.owner.Email,prod.Manager_Email__c,'chandra.s@proseraa.com'};
                    mail.setToAddresses(toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                ccTo.add('manjunath.s@proseraa.com');
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: https://moengage--proseraa.lightning.force.com/lightning/r/Lead/'+prod.id+'/view'+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}

 
Hello all
i am trying to design a trigger - when lead status is closed converted - The Fields  (Company,phone,email) in the lead object should be auto populated inside the fields of custom object new contact and opportunity objects (New_Contacts__c and Opportunity)

Cab anyone please help
Hello guys
 i need a small help, if i earn 4 certifications(Admin,Advance admin,App builder,developer) in a single year, how much maintenance fee do i need to pay
 
Hello All

How do i write test class for below Batch apex class, 
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c FROM Lead where No_Enquiry_Email_Sent__c=false AND Status=\'Enquiry\' And (CreatedDate = YESTERDAY OR LastModifiedDate = YESTERDAY) limit 1';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                
                // Step 2: Set list of people who should get the email
                String[] toAddresses = new String[] {prod.owner.Email,prod.Manager_Email__c,'chandra.s@proseraa.com'};
                    mail.setToAddresses(toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                ccTo.add('manjunath.s@proseraa.com');
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: https://moengage--proseraa.lightning.force.com/lightning/r/Lead/'+prod.id+'/view'+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}