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 achieve 75% code covrage

Hi,
When I checked below code in my dev org. It was almost cover 97% code covrage but when I applied same code in my sandbox it was showing only 10% of code covrage. Strange!
Please fing bellow batch class and test class:
global class SendEmailToDueDateTask implements Database.Batchable<sObject>  {
    map<string,list<task>> userEmailTasklistmap = new map<string,list<task>>();
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT ID,createddate,what.id,Owner.Email,OwnerId,owner.name,Status,ActivityDate,Subject from Task WHERE Status != 'Completed' and owner.isactive = true and owner.profile.id = '00eD0000001Qs3R']);
    }
    
    global void execute(Database.BatchableContext BC, List<Task> scope){
        for(Task Tsk : scope){
            if(!userEmailTasklistmap.Containskey(tsk.owner.email)){
                userEmailTasklistmap.put(tsk.owner.email, new list<task>());
            }
            userEmailTasklistmap.get(tsk.owner.email).add(tsk);
            
          }  
        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('Details of tasks due for today');                
                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;">Following tasks are pending. Please update the status.</td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Related To</th><th>Subject</th><th>Created Date</th><th> Due Date</th></tr>';
                for(task tsk : userEmailTasklistmap.get(email)){
                    
                    String duedate = '';
                    if (tsk.ActivityDate != null)
                        duedate = tsk.ActivityDate.format();                    
                    else
                        duedate = '';
                    String Subject = tsk.subject;
                    datetime dt = tsk.createddate;
                    string createddate = dt.format('M/d/yyyy');
                    //string what = https://ap2.salesforce.com/tsk.what.id;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ tsk.id;
                    string Clickhere = View;  
                    htmlBody += '<tr><td>' + Clickhere + '</td><td>' + Subject + '</td><td>' + createddate + '</td><td>' + duedate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);
    }
    global void finish(Database.BatchableContext BC){        
    }
}

Test Class:
@isTest 

public class SendEmailToDueDateTaskTest { 

static testMethod void testMethod1(){ 

        Profile pro = [SELECT Id FROM Profile WHERE Name='Standard User'];  
        User usr = new User(Alias = 'standt', Email='standarduser@tt.com',  
        EmailEncodingKey='UTF-8', LastName='Testing', 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'); 
            Task tsk = new Task(); 
                tsk.whatId = acc.Id;  
                tsk.Subject = 'Testing'; 
                tsk.Status = 'In Progress'; 
                tsk.Priority = 'Normal'; 
                tsk.ActivityDate = System.today(); 
                insert tsk ; 
                tsk=[SELECT id,Status FROM Task WHERE id=:tsk.Id]; 
                System.assertEquals(tsk.Status ,'In Progress'); 
            } 
            Test.StartTest(); 
                Database.executeBatch (new SendEmailToDueDateTask (),200); 
            Test.StopTest(); 
    } 
 }

Please help. Where I am wrong.
Best Answer chosen by Russell baker 1
Russell baker 1Russell baker 1
I got the solution. I put batch under  System.runAs(usr) { } and it was showing 97% covrage.

All Answers

Andries.NeyensAndries.Neyens
Take the Developer console and see what lines are not covered. It has something todo with the state the Org. Maybe the profile does not exists on your sandbox ? or the user is not unique ?
Russell baker 1Russell baker 1
I have checked profile exist and user is unique. but the lines which are not coverd :
global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT ID,createddate,what.id,Owner.Email,OwnerId,owner.name,Status,ActivityDate,Subject from Task WHERE Status != 'Completed' and owner.isactive = true and owner.profile.id = '00eD0000001Qs3R']);
    }
    
    global void execute(Database.BatchableContext BC, List<Task> scope){
        for(Task Tsk : scope){
            if(!userEmailTasklistmap.Containskey(tsk.owner.email)){
                userEmailTasklistmap.put(tsk.owner.email, new list<task>());
            }
            userEmailTasklistmap.get(tsk.owner.email).add(tsk);
            
          }  
        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('Details of tasks due for today');                
                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;">Following tasks are pending. Please update the status.</td>'+
                            +'</tr>'+
                        +'</table>';
 
                htmlBody +=  '<table border="1" style="border-collapse: collapse"><tr><th>Related To</th><th>Subject</th><th>Created Date</th><th> Due Date</th></tr>';
                for(task tsk : userEmailTasklistmap.get(email)){
                    
                    String duedate = '';
                    if (tsk.ActivityDate != null)
                        duedate = tsk.ActivityDate.format();                    
                    else
                        duedate = '';
                    String Subject = tsk.subject;
                    datetime dt = tsk.createddate;
                    string createddate = dt.format('M/d/yyyy');
                    //string what = https://ap2.salesforce.com/tsk.what.id;
                    string View = URL.getSalesforceBaseUrl().toExternalForm()+'/'+ tsk.id;
                    string Clickhere = View;  
                    htmlBody += '<tr><td>' + Clickhere + '</td><td>' + Subject + '</td><td>' + createddate + '</td><td>' + duedate + '</td></tr>';                    
                }
                 htmlBody += '</table><br>';
                 mail.sethtmlBody(htmlBody);
                 mails.add(mail);                    
            }
             if(mails.size()>0)
             Messaging.sendEmail(mails);

Above lines are in red. Does it means not covered by test class? I am not able to catch the thing. Please help.
Andries.NeyensAndries.Neyens
The lines in red are indeed the lines that were not covered by the unit test.
Can you try to change the unit test without the runAs syntax. To find out if it has something to do with the permissions of that user?
Maybe there is something different on profile between the 2 orgs
Russell baker 1Russell baker 1
I did and still get only 10% of code covrage.
Andries.NeyensAndries.Neyens
and what does the debug log say?
Russell baker 1Russell baker 1
It says " Line: 1, Column: 14
Global type must be contained inside of a global class"
Andries.NeyensAndries.Neyens
How did you get this message? From an anonymous window?
Out of curiosity I copy pasted this code into a Sandbox, and everything went well.
Maybe something else is going on and you should contact Support?
 
Andries.NeyensAndries.Neyens
another thing, is Task a public apex class in your org or are you referencing the sObject Task ?
Russell baker 1Russell baker 1
I got the solution. I put batch under  System.runAs(usr) { } and it was showing 97% covrage.
This was selected as the best answer