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
Russell baker 1Russell baker 1 

How to pull opportunity owner name in test class

Hi Experts,

I wrote a batch class to send email to opps owner when opportunity'c close date 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 wrire 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 for it.
Best Answer chosen by Russell baker 1
Amit Chaudhary 8Amit Chaudhary 8
Please try below code.
@isTest

public class SendEmailToopsownerTest  
{ 

	static testMethod void testMethod1()
	{ 
            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() -1 ; 
                opp.Ownerid = userinfo.getuserid();
                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(); 
    } 
 }
Let us know if this will help you

Thanks
Amit Chaudhary
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Please try below code.
@isTest

public class SendEmailToopsownerTest  
{ 

	static testMethod void testMethod1()
	{ 
            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() -1 ; 
                opp.Ownerid = userinfo.getuserid();
                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(); 
    } 
 }
Let us know if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
Russell baker 1Russell baker 1
Hi Amit,

Test Rus failed and when i checked in devloper console. I am getting below 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.: []
Amit Chaudhary 8Amit Chaudhary 8
Please check below for same issue
1) https://help.salesforce.com/apex/HTViewSolution?id=000002868&language=en_US



Check you Deliverabililty settings under Setup > Email Administration > Deliverability.  My issue was that we had the setting set to No Access.  It must be set to All Email. 

Let us know if this will help you

Thanks
Amit Chaudhary
Russell baker 1Russell baker 1
Thanks for your help!