0

I wrote a batch class to send email to opportunity owner when the opportunity's close date is passed.

global class SendEmailToopsowner implements Database.Batchable<sObject>  {

global Database.QueryLocator start(Database.BatchableContext BC){
    return Database.getQueryLocator([SELECT Id, Name, StageName, CloseDate, Owner.name, Owner.Email FROM Opportunity WHERE CloseDate < TODAY  and (StageName != 'closed-Won' or StageName != 'closed-Lost' or StageName != 'In-Production')  ]);
}

global void execute(Database.BatchableContext BC, List<opportunity> scope){
        map<string,list<opportunity>> userEmailTasklistmap = new map<string,list<opportunity>>();
        for(opportunity opp : scope){
        if(!userEmailTasklistmap.Containskey(opp.owner.email)){
            userEmailTasklistmap.put(opp.owner.email, new list<opportunity>());
        }
        userEmailTasklistmap.get(opp.owner.email).add(opp);

      }  
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();

        for(string email : userEmailTasklistmap.keyset()){

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            list<string> toAddresses = new list<string>();
            toAddresses.add(email);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Opportunity close date passed');                
            String username = userEmailTasklistmap.get(email)[0].owner.name;
            String htmlBody = '';

            htmlBody = '<table width="100%" border="0" cellspacing="0" cellpadding="8" align="center" bgcolor="#F7F7F7">'+
                        +'<tr>'+
                          +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri;line-height: 18px; color: #333;"><br />'+
                               +'<br />'+
                                +'Dear '+username+',</td>'+
                        +'</tr>'+
                        +'<tr>'+
                            +'<td style="font-size: 14px; font-weight: normal; font-family:Calibri; line-height: 18px; color: #333;"> Below are the list of opportunities under your name and the close dates have to be reviewed.Could you please advise new close date and insert your comments in the remarks section. </td>'+
                        +'</tr>'+
                    +'</table>';

            htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Clickhere</th><th>Name</th><th>StageName</th><th>CloseDate</th><th>Remark</th><th>Expected Close Date</th></tr>';
            for(opportunity opp : userEmailTasklistmap.get(email)){

                String CloseDate = '';
                if (opp.CloseDate != null)
                    CloseDate = opp.CloseDate.format();                    
                else
                    CloseDate = '';
                String Name = opp.Name;
                datetime dt = opp.CloseDate;
                string ClosedDate = dt.format('M/d/yyyy');
                string StageName = opp.StageName;
                string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ opp.id;
                //string clickhere = view;
                string Remark = '';
                string Expectedclosedate = '';                    
                htmlBody += '<tr><td>' + View +'</td><td>' + Name + '</td><td>' + StageName + '</td><td>' + CloseDate + '</td><td>' + Remark + '</td><td>' + Expectedclosedate + '</td></tr>';                    
            }
             htmlBody += '</table><br>';
             mail.sethtmlBody(htmlBody);
             mails.add(mail);                    
        }
         if(mails.size()>0)
         Messaging.sendEmail(mails);
}
global void finish(Database.BatchableContext BC){        
}
}

Then I tried to write Test class but not able to pull opportunity owner name and email in test class. below is my test class

 @isTest(seeAllData = true) 

public class SendEmailToopsownerTest  { 

static testMethod void testMethod1(){ 

    Profile pro = [SELECT Id FROM Profile WHERE Name='!Sales'];  
    User usr = new User( Alias = 'standt', Email='standarduser@tt.com',  
    EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',  
    LocaleSidKey='en_US', ProfileId = pro.Id,  
    TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@tt.com'); 

    System.runAs(usr) { 
        Account acc = new Account(); 
            acc.Name = 'Test Account'; 
            insert acc; 
            acc=[SELECT id,Name FROM account WHERE id=:acc.Id]; 
            System.assertEquals(acc.Name,'Test Account'); 
        Opportunity opp = new Opportunity(); 
            opp.AccountId = acc.Id;  
            opp.Name = 'Testing'; 
            opp.StageName = 'Prospecting'; 
            opp.CloseDate = System.Today(); 
            opp.Owner.name = 'Testing1';
            opp.Owner.Email = 'standarduser@tt.com';                
            insert opp ; 
            opp=[SELECT id,Name,StageName,CloseDate,Owner.name,Owner.Email FROM Opportunity WHERE id=:opp.Id]; 
            System.assertEquals(opp.StageName ,'Prospecting'); 
         }
         Test.StartTest(); 
            Database.executeBatch (new SendEmailToopsownerTest (),200); 
        Test.StopTest(); 
} 
}

Kindly help me to write test class.

0

Use the below test class it will give the coverage of 97%. If you want it to be 100% then you have to make another method without close date of Opportunity.

@isTest(seeAllData = true) 

public class SendEmailToopsownerTest  { 

static testMethod void testMethod1(){ 

    Profile pro = [SELECT Id FROM Profile WHERE Name='!Sales'];
    User usr = new User( Alias = 'standt', Email='standarduser@tt.com',  
    EmailEncodingKey='UTF-8', LastName='Testing1', LanguageLocaleKey='en_US',  
    LocaleSidKey='en_US', ProfileId = pro.Id,  
    TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@tt.com'); 
Opportunity opp;
    System.runAs(usr) { 
        Account acc = new Account(); 
            acc.Name = 'Test Account'; 
            insert acc; 
            acc=[SELECT id,Name FROM account WHERE id=:acc.Id]; 
            System.assertEquals(acc.Name,'Test Account'); 
        opp = new Opportunity(); 
            opp.AccountId = acc.Id;  
            opp.Name = 'Testing'; 
            opp.StageName = 'Prospecting'; 
            opp.CloseDate = System.Today(); 
            //opp.Owner.name = 'Testing1';
            //opp.Owner.Email = 'standarduser@tt.com';                
            insert opp ; 
            opp=[SELECT id,Name,StageName,CloseDate,Owner.name,Owner.Email FROM Opportunity WHERE id=:opp.Id]; 
            System.assertEquals(opp.StageName ,'Prospecting'); 
         }
         Test.StartTest(); 
            Database.executeBatch(new SendEmailToopsowner(),200);
        Test.StopTest(); 
} 
}
| improve this answer | |
  • Getting error: System.EmailException: SendEmail failed. First exception on row 0; first error: NO_MASS_MAIL_PERMISSION, Single email is not enabled for your organization or profile.: [] – Russel baker 1 May 18 '16 at 10:08
  • Sorry for late response. For this you have to make a setting in your salesforce org. Please find the below steps--->>>Check you Deliverabililty settings under Setup > Email Administration > Deliverability. Here under the "Deliverability" heading under "InformationAccess to Send Email " in the picklist section you have to give "All Email" Access. This will resolve your problem. – user3598908 May 23 '16 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.