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
ChrisludoviceChrisludovice 

Scheduled Apex Test Class - some lines are not covered

Hi,

I am only getting 36% of my test class. Can you help me on this one?

Thanks.

SCHEDULED APEX:

/**
*author Chris Ludovice
*@date  4.15.2019
*description Schedulable apex class(invokable) responsible for missed invoices email alert.
@revision(s)
 */

global class SS_EscalationAlertsMIR implements Schedulable {
    
       // initialize email related variables
       public String htmlSP = '';
       public String htmlMgr = '';
       public String htmlClevel = '';
       public String htmlSend = '';
       public String subjectSP = 'First Escalation: Accounts with Missed Invoices';
       public String subjectMgr = 'Second Escalation: Accounts with Missed Invoices'; 
       public String subjectClevel = 'Third Escalation: Accounts with Missed Invoices'; 
       public String subjectSend = ''; 
       public String htmlAppendSP = '----------First Escalation: Accounts with Missed Invoices----------</br>';
       public String htmlAppendMgr = '----------Second Escalation: Accounts with Missed Invoices----------</br>';
       public String htmlMgr15 = '';
       public String htmlMgr30 = '';
       public String htmlC15 = '';
       public String htmlC30 = ''; 
    
       public String dateFormatString = 'yyyy-MM-dd';
        
       public String[] toAddressesSP = new List<String>(); // holds SP's email... 
       public String[] toAddressesMgr = new List<String>(); // holds Manager's email...   
       public String[] toAddressesClevel = new List<String>(); // holds Clevel's email...  
       public String[] toAddresses = new List<String>(); // holds the actual email recipient..
    
       // initialize sp <td> variables...
       public Date dSP = system.today();
       public Datetime dtSP = system.now();
       public String dateStringSP = '';
       public Set<String> uniqueSP = new Set<String>();
    
          // initialize mgr <td> variables...
       public Decimal s = 0.00;
       public Date dMgr = system.today();
       public Datetime dtMgr = system.now();
       public String dateStringMgr = '';
       public Set<String> uniqueMgr = new Set<String>();
    
       // initialize clevel <td> variables...
       public Decimal m = 0.00;
       Date dClevel = system.today();
       Datetime dtClevel = system.now();
       String dateStringClevel = '';
   
    global void execute(SchedulableContext ctx) {
        
         // remove Name='Report-Scheduler-Missed-Invoice after testing...
        
        // render sp missed invoice (>=15days overdue) and < 30?
         List<Account> spList = [SELECT Id, Sales_Rep__r.User_account__r.Email, Name,Latest_Service_End_Date__c,Days_Overdue_Missed_Invoice__c,Sales_Rep__r.Name FROM Account
            WHERE Name='Report-Scheduler-Missed-Invoice' AND (Days_Overdue_Missed_Invoice__c >= 15 AND Days_Overdue_Missed_Invoice__c < 30) AND Current_Contract_Status__c = 'Active'];        
       
       // render mgr missed invoice (>=30days overdue) and < 45?
         List<Account> mgrList = [SELECT Id, Sales_Rep__r.User_account__r.Manager.Email, Name,Latest_Service_End_Date__c,Days_Overdue_Missed_Invoice__c,Sales_Rep__r.Name FROM Account
            WHERE Name='Report-Scheduler-Missed-Invoice' AND (Days_Overdue_Missed_Invoice__c >= 30 AND Days_Overdue_Missed_Invoice__c < 45) AND Current_Contract_Status__c = 'Active'];      
 
       // render clevel missed invoice (>=45days overdue)
         List<Account> cList = [SELECT Id, Name,Latest_Service_End_Date__c,Days_Overdue_Missed_Invoice__c,Sales_Rep__r.Name FROM Account
            WHERE Name='Report-Scheduler-Missed-Invoice' AND Days_Overdue_Missed_Invoice__c >= 45 AND Current_Contract_Status__c = 'Active'];  
      
       // initialize html table variables for each email body...
                
      if(spList.size()>0){   // check if SP missed invoice SOQL has returned row(s)..  
      
       htmlSP = '<p>You are receiving this email as one of your accounts may not have billed at least 15 days after its expected subscription end date. Please raise corresponding subscription/membership opportunity.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+spList.size()+'</br><i>As of:&nbsp;'+datetime.now().format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';          
      
       for(Account accSP:spList)
        {
            toAddressesSP.Add(accSP.Sales_Rep__r.User_account__r.Email); // add emails in SP array..  
            dSP = accSP.Latest_Service_End_Date__c;
            Datetime dtSP = Datetime.newInstance(dSP.year(), dSP.month(),dSP.day());
            dateStringSP = dtSP.format(dateFormatString);
            htmlSP += '<tr><td><a target="_blank" href="'+system.label.Salesforce_Instance_URL+accSP.Id+'">'+ accSP.Name + '</a></td><td>'+accSP.Sales_Rep__r.Name+'</td><td>' + dateStringSP + '</td><td>'+accSP.Days_Overdue_Missed_Invoice__c+'</td></tr>';

        }      
             //close table...
            htmlSP += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';
            system.debug(htmlSP);  
            
            // get unique SP emails in the array...
            uniqueSP.addAll(toAddressesSP);
            toAddresses.AddAll(uniqueSP);
          
              subjectSend = subjectSP;
            htmlSend = htmlSP;
              SS_EmailUtility.SendEmail(htmlSend, toAddresses, subjectSend); 
          
      } // end of IF for SP...
        
      if(mgrList.size()>0){   // check if Mgr missed invoice SOQL has returned row(s)..  
      
       htmlMgr = '<p>Being the manager of the identified account managers, listed accounts have not been billed for at least 30 days.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+mgrList.size()+'</br><i>As of:&nbsp;'+datetime.now().format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';  
       htmlMgr15 = '<p>You are receiving this email as one of your accounts may not have billed at least 15 days after its expected subscription end date. Please raise corresponding subscription/membership opportunity.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+mgrList.size()+'</br><i>As of:&nbsp;'+datetime.now().addDays(-15).format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';  
          
       for(Account accMgr:mgrList)
        {
       
            toAddressesMgr.Add(accMgr.Sales_Rep__r.User_account__r.Manager.Email); // add emails in Mgr array..
            dMgr = accMgr.Latest_Service_End_Date__c;
            dtMgr = Datetime.newInstance(dMgr.year(), dMgr.month(),dMgr.day());
            dateStringMgr= dtMgr.format(dateFormatString);
            s = accMgr.Days_Overdue_Missed_Invoice__c-15;
            htmlMgr += '<tr><td><a target="_blank" href=""'+system.label.Salesforce_Instance_URL+accMgr.Id+'">'+accMgr.Name + '</a></td><td>'+accMgr.Sales_Rep__r.Name+'</td><td>' + dateStringMgr + '</td><td>'+accMgr.Days_Overdue_Missed_Invoice__c+'</td></tr>';
            htmlMgr15 += '<tr><td><a target="_blank" href=""'+system.label.Salesforce_Instance_URL+accMgr.Id+'">'+accMgr.Name + '</a></td><td>'+accMgr.Sales_Rep__r.Name+'</td><td>' + Date.valueOf(dateStringMgr).format() + '</td><td>'+s+'</td></tr>';

            
        } 
             //close table...
            htmlMgr += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';
            htmlMgr15 += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';
              htmlAppendSP += htmlMgr15;
            htmlMgr += htmlAppendSP;    
            system.debug(htmlMgr);              
             
            // get unique Mgr emails in the array...           
            uniqueMgr.addAll(toAddressesMgr);
            toAddresses.AddAll(uniqueMgr);
          
              subjectSP = 'Second Escalation: Accounts with Missed Invoices';
              subjectSend = subjectMgr;
            htmlSend = htmlMgr;
              SS_EmailUtility.SendEmail(htmlSend, toAddresses, subjectSend); 
          
      } // end of IF for Mgr...
    
      if(cList.size()>0){   // check if Clevel missed invoice SOQL has returned row(s)..  
      
       htmlClevel = '<p>Escalating to Senior Executive Group as accounts listed below have not been billed for at least 45 days.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+cList.size()+'</br><i>As of:&nbsp;'+datetime.now().format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';          
       htmlC30 = '<p>Being the manager of the identified account managers, listed accounts have not been billed for at least 30 days.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+cList.size()+'</br><i>As of:&nbsp;'+datetime.now().addDays(-15).format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';  
       htmlC15 = '<p>You are receiving this email as one of your accounts may not have billed at least 15 days after its expected subscription end date. Please raise corresponding subscription/membership opportunity.</p><table border="1" style="border-collapse: collapse;text-align:left"><caption style="text-align:left"><u><b>Missed Invoice Summary Data:</b></u></br>Total Records:&nbsp;'+cList.size()+'</br><i>As of:&nbsp;'+datetime.now().addDays(-30).format()+'</i></caption><tr style="text-align:left"><th>Account Name</th><th>Account Owner</th><th>Last Service EndDate</th><th>Days Overdue</th></tr>';    
          
       for(Account accClevel:cList)
        {
       
            dClevel = accClevel.Latest_Service_End_Date__c;
            dtClevel = Datetime.newInstance(dClevel.year(), dClevel.month(),dClevel.day());
            dateStringClevel= dtClevel.format(dateFormatString);
            s = accClevel.Days_Overdue_Missed_Invoice__c-30;
            m = accClevel.Days_Overdue_Missed_Invoice__c-15;
            htmlClevel += '<tr><td><a target="_blank" href=""'+system.label.Salesforce_Instance_URL+accClevel.Id+'">'+accClevel.Name + '</a></td><td>'+accClevel.Sales_Rep__r.Name+'</td><td>' + dateStringClevel + '</td><td>'+accClevel.Days_Overdue_Missed_Invoice__c+'</td></tr>';

            htmlC15 += '<tr><td><a target="_blank" href=""'+system.label.Salesforce_Instance_URL+accClevel.Id+'">'+accClevel.Name + '</a></td><td>'+accClevel.Sales_Rep__r.Name+'</td><td>' + Date.valueOf(dateStringClevel).format() + '</td><td>'+s+'</td></tr>';
            htmlC30 += '<tr><td><a target="_blank" href=""'+system.label.Salesforce_Instance_URL+accClevel.Id+'">'+accClevel.Name + '</a></td><td>'+accClevel.Sales_Rep__r.Name+'</td><td>' + Date.valueOf(dateStringClevel).format() + '</td><td>'+m+'</td></tr>';
            
        } 
             
      // Select all user emails from Clevel PG...
      Group grp = [SELECT Id FROM Group Where DeveloperName ='Clevel_Users']; // fetch PG Id
      List<GroupMember> grpm = [SELECT UserOrGroupId FROM GroupMember Where GroupId =:grp.Id]; // fetch Group Users Id...
      Set<Id> grpmIds = new Set<Id>();  
      for(GroupMember grpmSet :grpm){
          grpmIds.add(grpmSet.UserOrGroupId);
            }
      List<User> cUsers = [SELECT Email FROM User Where Id=:grpmIds]; // fetch cleveluser's email.
        for(User cu: cUsers)  {
         toAddressesClevel.Add(cu.Email);  // add emails in clevel array..
         system.debug('Clevel Emails: '+toAddressesClevel); 
        }          
          
     //close table...
     htmlClevel += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';
     system.debug(htmlClevel);              
     toAddresses = toAddressesClevel;               
     subjectClevel = 'Third Escalation: Accounts with Missed Invoices';
     subjectSend = subjectClevel;
          
     htmlC15 += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';
     htmlC30 += '</table></br>************************************************</br>This is an auto-generated email, please DO NOT REPLY.</br> ************************************************</br></br>';     
     htmlAppendSP += htmlC15;
     htmlAppendMgr += htmlC30;
     htmlAppendMgr += htmlAppendSP;     
     htmlClevel += htmlAppendMgr;
    
     htmlSend = htmlClevel;
     SS_EmailUtility.SendEmail(htmlSend, toAddresses, subjectSend); 
          
      } // end of IF for Clevel...
  
               
     } // end of execute constructor...
    
} // end of main class..

***********************************************************************

TEST CLASS:

@isTest 
private class SS_EscalationAlertsMIRTest {
    
     // Dummy CRON expression: midnight on May 1.
    // Because this is a test, job executes
   // immediately after Test.stopTest().
   
   public static String CRON_EXP = '0 0 0 1 5 ? 2019';
    
    static testmethod void testScheduledJob() { 
                
       // Create test Account record
        Account accs = new Account();
        Date servDate = Date.today().addDays(-45);
        accs.Name = 'Test';
        accs.Latest_Service_End_Date__c = servDate;
        
        // select profile.....
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];     
              
        User ManagerToCreate = new User(); //Create a manager user
        ManagerToCreate.Email='ManagerUserA@testorganise.com';
        ManagerToCreate.Alias = 'standard';
        ManagerToCreate.EmailEncodingKey='UTF-8';
        ManagerToCreate.LastName='Manager Test';
        ManagerToCreate.LanguageLocaleKey='en_US';
        ManagerToCreate.LocaleSidKey='en_US';
        ManagerToCreate.TimeZoneSidKey='America/Los_Angeles';
        ManagerToCreate.UserName='ManagerUserA@testorganise.com';
        ManagerToCreate.ProfileId = p.Id;
        insert ManagerToCreate;

        User userToCreate = new User(); // Create an Employee
        userToCreate.Email='UserA@testorganise.com';
        userToCreate.Alias = 'standard';
        userToCreate.EmailEncodingKey='UTF-8';
        userToCreate.LastName='User Test';
        userToCreate.LanguageLocaleKey='en_US';
        userToCreate.LocaleSidKey='en_US';
        userToCreate.TimeZoneSidKey='America/Los_Angeles';
        userToCreate.UserName='UserA@testorganise.com';
        userToCreate.ManagerId = ManagerToCreate.Id;  // Assign Manager to an Employee
        userToCreate.ProfileId = p.Id;
        insert userToCreate;
        
                                                           
       Test.startTest();
        
       system.runAs(userToCreate){
        
       // Setup shipserv person test data
       ShipServ_People__c sp = new ShipServ_People__c(Name='last', User_account__c=userToCreate.Id);
       insert sp;
       system.debug('id of user:'+sp.User_account__c+sp.User_account__c); 
            
        accs.Sales_Rep__c = sp.Id;   
        insert accs;  
        
        // Get the accounts that were just inserted       
        list<Account> uRetrieve = [select id from account]; //retrieve the record
        integer acc = uRetrieve.size();
        system.assertEquals(1,acc);//Test that the record is inserted
                       
        //Create public group...
        Group gp = new Group(Name = 'Test', DeveloperName='test');
        insert gp;
                      
        // Create group member...
        GroupMember gpm = new GroupMember();
        gpm.GroupId = gp.Id;
        gpm.UserOrGroupId = userToCreate.Id;
        insert(gpm);        
        system.debug('group member inserted:'+gpm.id);
           
        // Get the group member that's just inserted 
        list<GroupMember>gpmRetrieve = [select id from GroupMember where Group.DeveloperName='test']; //retrieve the record
        integer gpm2 = gpmRetrieve.size();
        system.assertEquals(1,gpm2);//Test that the record is inserted
           
       Id[] fixedSearchResults = new Id[2];
       fixedSearchResults[0] = accs.Id;
           
           
       // create an instance of the class... 
       SS_EscalationAlertsMIR mir = new SS_EscalationAlertsMIR();
       mir.htmlSP += 'test'+acc+datetime.now().format();
       mir.execute(null);    
          
       } // end of system.runAs...
                    
          // Schedule the test job
        String jobId = System.schedule('ScheduledApexTest',
            CRON_EXP, 
            new SS_EscalationAlertsMIR());
        
       // SS_EmailUtility.SendEmail('Unit Test X', new List<String>{'test@test.com'});
        
        Test.stopTest(); 

    }
}
Best Answer chosen by Chrisludovice
Ramesh DRamesh D
Hi Chris,
Try this
@isTest 
private class SS_EscalationAlertsMIRTest {
    
    // Dummy CRON expression: midnight on May 1.
    // Because this is a test, job executes
    // immediately after Test.stopTest().
    
    public static String CRON_EXP = '0 0 0 1 5 ? 2019';
    
    @testSetup static void DataSetup() {
        // Create test Account record
        Account accs = new Account();
        Date servDate = Date.today().addDays(-45);
        accs.Name = 'Report-Scheduler-Missed-Invoice';
        accs.Latest_Service_End_Date__c = servDate;
        accs.Days_Overdue_Missed_Invoice__c=16;
        accs.Current_Contract_Status__c='Active';
        // select profile.....
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];     
        
        User ManagerToCreate = new User(); //Create a manager user
        ManagerToCreate.Email='ManagerUserA@testorganise.com';
        ManagerToCreate.Alias = 'standard';
        ManagerToCreate.EmailEncodingKey='UTF-8';
        ManagerToCreate.LastName='Manager Test';
        ManagerToCreate.LanguageLocaleKey='en_US';
        ManagerToCreate.LocaleSidKey='en_US';
        ManagerToCreate.TimeZoneSidKey='America/Los_Angeles';
        ManagerToCreate.UserName='ManagerUserA@testorganise.com';
        ManagerToCreate.ProfileId = p.Id;
        insert ManagerToCreate;
        
        User userToCreate = new User(); // Create an Employee
        userToCreate.Email='UserA@testorganise.com';
        userToCreate.Alias = 'standard';
        userToCreate.EmailEncodingKey='UTF-8';
        userToCreate.LastName='User Test';
        userToCreate.LanguageLocaleKey='en_US';
        userToCreate.LocaleSidKey='en_US';
        userToCreate.TimeZoneSidKey='America/Los_Angeles';
        userToCreate.UserName='UserA@testorganise.com';
        userToCreate.ManagerId = ManagerToCreate.Id;  // Assign Manager to an Employee
        userToCreate.ProfileId = p.Id;
        insert userToCreate;
        
        insert accs; 
    }
    static testmethod void Scene1()
    {
        Test.startTest();
        account accs = [select id from account limit 1];
        user userToCreate=[select id,email from user where email='UserA@testorganise.com' limit 1];
        testScheduledJob(accs,userToCreate,'testNew');
        accs.Days_Overdue_Missed_Invoice__c=36;
        update accs;
        testScheduledJob(accs,userToCreate,'TestNew1');  
        accs.Days_Overdue_Missed_Invoice__c=46;
        update accs;
        testScheduledJob(accs,userToCreate,'Clevel_Users');   
        Test.stopTest();
    }
    static void testScheduledJob( account accs,user userToCreate,string groupname) { 
        
        system.runAs(userToCreate){
            
            // Setup shipserv person test data
            // ShipServ_People__c sp = new ShipServ_People__c(Name='last', User_account__c=userToCreate.Id);
            // insert sp;
            // system.debug('id of user:'+sp.User_account__c+sp.User_account__c); 
            
            // accs.Sales_Rep__c = sp.Id;   
            
            
            // Get the accounts that were just inserted       
            list<Account> uRetrieve = [select id from account]; //retrieve the record
            integer acc = uRetrieve.size();
            system.assertEquals(1,acc);//Test that the record is inserted
            
            //Create public group...
            Group gp = new Group(Name = groupname, DeveloperName=groupname);
            insert gp;
            
            // Create group member...
            GroupMember gpm = new GroupMember();
            gpm.GroupId = gp.Id;
            gpm.UserOrGroupId = userToCreate.Id;
            insert(gpm);        
            system.debug('group member inserted:'+gpm.id);
            
            // Get the group member that's just inserted 
            list<GroupMember>gpmRetrieve = [select id from GroupMember where Group.DeveloperName=:groupname]; //retrieve the record
            integer gpm2 = gpmRetrieve.size();
            system.assertEquals(1,gpm2);//Test that the record is inserted
            
            Id[] fixedSearchResults = new Id[2];
            fixedSearchResults[0] = accs.Id;            
            
            // create an instance of the class... 
            SS_EscalationAlertsMIR mir = new SS_EscalationAlertsMIR();
            mir.htmlSP += 'test'+acc+datetime.now().format();
            mir.execute(null);    
            
        } // end of system.runAs...
        
        // Schedule the test job
        String jobId = System.schedule('ScheduledApexTest'+groupname,
                                       CRON_EXP, 
                                       new SS_EscalationAlertsMIR());
        
    }
}

I hope you find the above solution helpful. If it does mark as best answer to help others too.
Thanks,
Ramesh D
 

All Answers

Ramesh DRamesh D
Can you post a schreenshot of what lines not covered?

 
ChrisludoviceChrisludovice

Hi @Ramesh,

See below lines:

Line 72-193

User-added image

Line 99-119

User-added image

Line 123-150

User-added image

Line 155-182

 User-added image

Thanks.

Regards,

Chris

Ramesh DRamesh D
Hi Chris,
Try this
@isTest 
private class SS_EscalationAlertsMIRTest {
    
    // Dummy CRON expression: midnight on May 1.
    // Because this is a test, job executes
    // immediately after Test.stopTest().
    
    public static String CRON_EXP = '0 0 0 1 5 ? 2019';
    
    @testSetup static void DataSetup() {
        // Create test Account record
        Account accs = new Account();
        Date servDate = Date.today().addDays(-45);
        accs.Name = 'Report-Scheduler-Missed-Invoice';
        accs.Latest_Service_End_Date__c = servDate;
        accs.Days_Overdue_Missed_Invoice__c=16;
        accs.Current_Contract_Status__c='Active';
        // select profile.....
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];     
        
        User ManagerToCreate = new User(); //Create a manager user
        ManagerToCreate.Email='ManagerUserA@testorganise.com';
        ManagerToCreate.Alias = 'standard';
        ManagerToCreate.EmailEncodingKey='UTF-8';
        ManagerToCreate.LastName='Manager Test';
        ManagerToCreate.LanguageLocaleKey='en_US';
        ManagerToCreate.LocaleSidKey='en_US';
        ManagerToCreate.TimeZoneSidKey='America/Los_Angeles';
        ManagerToCreate.UserName='ManagerUserA@testorganise.com';
        ManagerToCreate.ProfileId = p.Id;
        insert ManagerToCreate;
        
        User userToCreate = new User(); // Create an Employee
        userToCreate.Email='UserA@testorganise.com';
        userToCreate.Alias = 'standard';
        userToCreate.EmailEncodingKey='UTF-8';
        userToCreate.LastName='User Test';
        userToCreate.LanguageLocaleKey='en_US';
        userToCreate.LocaleSidKey='en_US';
        userToCreate.TimeZoneSidKey='America/Los_Angeles';
        userToCreate.UserName='UserA@testorganise.com';
        userToCreate.ManagerId = ManagerToCreate.Id;  // Assign Manager to an Employee
        userToCreate.ProfileId = p.Id;
        insert userToCreate;
        
        insert accs; 
    }
    static testmethod void Scene1()
    {
        Test.startTest();
        account accs = [select id from account limit 1];
        user userToCreate=[select id,email from user where email='UserA@testorganise.com' limit 1];
        testScheduledJob(accs,userToCreate,'testNew');
        accs.Days_Overdue_Missed_Invoice__c=36;
        update accs;
        testScheduledJob(accs,userToCreate,'TestNew1');  
        accs.Days_Overdue_Missed_Invoice__c=46;
        update accs;
        testScheduledJob(accs,userToCreate,'Clevel_Users');   
        Test.stopTest();
    }
    static void testScheduledJob( account accs,user userToCreate,string groupname) { 
        
        system.runAs(userToCreate){
            
            // Setup shipserv person test data
            // ShipServ_People__c sp = new ShipServ_People__c(Name='last', User_account__c=userToCreate.Id);
            // insert sp;
            // system.debug('id of user:'+sp.User_account__c+sp.User_account__c); 
            
            // accs.Sales_Rep__c = sp.Id;   
            
            
            // Get the accounts that were just inserted       
            list<Account> uRetrieve = [select id from account]; //retrieve the record
            integer acc = uRetrieve.size();
            system.assertEquals(1,acc);//Test that the record is inserted
            
            //Create public group...
            Group gp = new Group(Name = groupname, DeveloperName=groupname);
            insert gp;
            
            // Create group member...
            GroupMember gpm = new GroupMember();
            gpm.GroupId = gp.Id;
            gpm.UserOrGroupId = userToCreate.Id;
            insert(gpm);        
            system.debug('group member inserted:'+gpm.id);
            
            // Get the group member that's just inserted 
            list<GroupMember>gpmRetrieve = [select id from GroupMember where Group.DeveloperName=:groupname]; //retrieve the record
            integer gpm2 = gpmRetrieve.size();
            system.assertEquals(1,gpm2);//Test that the record is inserted
            
            Id[] fixedSearchResults = new Id[2];
            fixedSearchResults[0] = accs.Id;            
            
            // create an instance of the class... 
            SS_EscalationAlertsMIR mir = new SS_EscalationAlertsMIR();
            mir.htmlSP += 'test'+acc+datetime.now().format();
            mir.execute(null);    
            
        } // end of system.runAs...
        
        // Schedule the test job
        String jobId = System.schedule('ScheduledApexTest'+groupname,
                                       CRON_EXP, 
                                       new SS_EscalationAlertsMIR());
        
    }
}

I hope you find the above solution helpful. If it does mark as best answer to help others too.
Thanks,
Ramesh D
 
This was selected as the best answer
ChrisludoviceChrisludovice
Thanks Ramesh!

But Days_Overdue_Missed_Invoice__c and Current_Contract_Status__c are both formula fieds so they're not writeUser-added imageable. 
ChrisludoviceChrisludovice
Or can you kindly explain to me, what i am missing or doing wrong.

Thanks.
ChrisludoviceChrisludovice
Hi Ramesh,

Already figured it out, I am missing a contract record tied to an account, for the formula field to meet its criteria... getting now 86% coverage... just need to work on the remaining uncovered lines...

Your code works! 

Thanks.

Regards,
Chris