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
Amol ChAmol Ch 

Error in test class while Mass updating not cover code coverage

Below is the apex class which will call from trigger on after update event
public class OptyCreationForDispFootPres
    {
    public static void createopty(List<Patient_Services__c> PSlist, map<id,Patient_Services__c> oldPSMap)
        {
        	set<string> PatientID= new set<string>();
            List<Patient_Services__c> psnewlist = new List<Patient_Services__c>();
            List<Rate_Card__c> rcardnewlist =new List<Rate_Card__c>();
            List<sked__Job__c> joblist=new List<sked__Job__c>();
            List<sked__Job__c> joblistnw=new List<sked__Job__c>();
            Set<OpportunityLineItem> olilist=new Set<OpportunityLineItem>();
            List<OpportunityLineItem> olilist1=new List<OpportunityLineItem>(); 
            List<Opportunity> oplist=new List<Opportunity>();
            List<Account> accname = new List<Account>();
            Integer extid;
            String RecNamePodwP,RecNameAudwP,RecNameDiteticscwP,RecNameDivTrpwP,RecNameMntHlthwP,RecNameOccTrpwP,RecNameOptmwP,RecNamePhytrpwP,RecNamePhyTrpExClswP,RecNameRegNrsewP,RecNameSpchTrpwP;
            String myeffDate = date.today().format();
            Date Nxtoptycreationdate,Closedate;
            String BillableCycle,InvoiceSentby,InvoiceSentTo,Accntterms,RateCardtype;
            List<Patient_Services__c> psupdlist= new List<Patient_Services__c>();
            Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe() ;
            Map<String,Schema.RecordTypeInfo> recordType = sObjectMap.get('Opportunity').getDescribe().getRecordTypeInfosByName();
            ID RtIdPodwP,RtIdAudwP,RtIdDiteticscwP,RtIdDivTrpwP,RtIdMntHlthwP,RtIdOccTrpwP,RtIdOptmwP,RtIdPhytrpwP,RtIdPhyTrpExClswP,RtIdRegNrsewP,RtIdSpchTrpwP;
            User vLstUserop = [select id from User where Opportunity_Owner__c=true and IsActive=true LIMIT 1];
            List<Opportunity> opty=[select Id,Opty_No__c from Opportunity order by CreatedDate DESC limit 1];
             
             
             for(Patient_Services__c PS :PSlist)
            {
                if(ps.Ready_for_Billing__c==true && ps.Dispensing_Footwear_F049__c==true && oldPSMap.get(ps.id).Dispensing_Footwear_F049__c ==false)
               
                {
                    PatientID.add(ps.id);
                }
             
            }
            
            psnewlist = [select id,Medicare_Account__c,Emergency_Visit__c,DVA_Code__c,Patient_DVA_Number__c,Patient_Medicare_No__c,
            Podiatry_Services__c,Job_Start_Datew_otime__c,Dispensing_Footwear_F049__c,DVA_Account__c,Initial_Consultation__c,
            Subsequent_Consulation__c,RecordType.name,Patient__r.Medicare_Account__c,Patient__r.Medicare_Account__r.Name,
            Patient__r.DVA_Account__c,Patient__r.DVA_Account__r.Name,Who_to_Invoice__c,Patient_Service_Lunch__c,
            Patient_Service_Invoice_Duration__c,Job_allocation_count__c,Job_Invoice_Start__c,Job_Invoice_Duration__c,Job_Invoice_Finish__c,
            Lunch_Break_Duration_from_Job__c,Job_Billable__c,Job__c,Patient_Service_Invoice_Finish__c,Patient_Service_Invoice_Start__c,
            Job_Type__c,Resource_Name__c,Service_Type__c from Patient_Services__c where id in :PatientID ]; 
            
                        
             if(PatientID.size()>0)
            {
            
            system.debug('++++++++++++++++++++++++++'+psnewlist.size());
           
                List<Rate_Card__c> ratecardlist = new List<Rate_Card__c>();
            
                ratecardlist=[Select id,Next_Opportunity_Creation_Date__c,Which_Rate_to_use_withpatients__c,Footwear_Dispensed__c,
                Emergency_Visit__c,PricebookEntryId__c,Job_Type__c,Assessment__c,Travel__c,Report__c,Treatment_Rate__c,Menu_Review__c,
                Hourly_Rate__c,Account_Name__c,Other__c,Next_Billable_Date__c,Opportunity_Creation_Frequency__c,Invoice_sent_by__c,Invoice_sent_to__c,Account_Terms__c,
                Rate_Card_Type__c from Rate_Card__c where Account_Name__c='Department of Veteran Affairs'];
                
                   // String DVAaccId = pslines.Patient__r.DVA_Account__c;
                   //  String DVAaccName = pslines.Patient__r.DVA_Account__r.Name;
            
                    
                for(Patient_Services__c pslines : psnewlist)
                {   for(Rate_Card__c rcard : ratecardlist)
                    {
                    if(rcard.Job_Type__c ==pslines.Job_Type__c && rcard.Rate_Card_Type__c == pslines.Service_Type__c)
                    rcardnewlist.add(rcard);
                    }
                }
                
                if(rcardnewlist.size()>0)
                {
                
               
                
                    for(Patient_Services__c pslines : psnewlist)
                    {
                   
                         if(pslines.RecordType.name =='Podiatry')
                        {
                            RtIdPodwP = recordType.get('Podiatry with Patients').getRecordTypeId();
                            RecNamePodwP=recordType.get('Podiatry with Patients').getName();
                            
                            System.debug('!!!!!!!!!!!!!!!!!!!!!!!!!!'+pslines.RecordType.name);
                       }
                     else if(pslines.RecordType.name =='Audiology')
                             {
                                RtIdAudwP = recordType.get('Audiology with Patients').getRecordTypeId();
                                RecNameAudwP=recordType.get('Audiology with Patients').getName();
                              }
                            else if(pslines.RecordType.name =='Dietetics')
                                {
                                    RtIdDiteticscwP = recordType.get('Dietetics with Patients').getRecordTypeId();
                                    RecNameDiteticscwP=recordType.get('Dietetics with Patients').getName();
                                }
                            else if(pslines.RecordType.name =='Diversional Therapy')
                                {
                                    RtIdDivTrpwP = recordType.get('Diversional Therapy with Patients').getRecordTypeId();
                                    RecNameDivTrpwP=recordType.get('Diversional Therapy with Patients').getName();
                                }
                            else if(pslines.RecordType.name =='Mental Health')
                            {
                                RtIdMntHlthwP = recordType.get('Mental Health with Patients').getRecordTypeId();
                                RecNameMntHlthwP = recordType.get('Mental Health with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Occupational Therapy')
                            {
                                RtIdOccTrpwP = recordType.get('Occupational Therapy with Patients').getRecordTypeId();
                                RecNameOccTrpwP=recordType.get('Occupational Therapy with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Optometry')
                            {
                                RtIdOptmwP = recordType.get('Optometry with Patients').getRecordTypeId();
                                RecNameOptmwP=recordType.get('Optometry with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Physiotherapy')
                            {
                                RtIdPhytrpwP = recordType.get('Physiotherapy with Patients').getRecordTypeId();
                                RecNamePhytrpwP=recordType.get('Physiotherapy with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Physiotherapy Exercise Classes')
                            {
                                RtIdPhyTrpExClswP = recordType.get('Physiotherapy Exercise Classes with Patients').getRecordTypeId();
                                RecNamePhyTrpExClswP=recordType.get('Physiotherapy Exercise Classes with Patients').getName();
                            }
                            else if(pslines.RecordType.name =='Registered Nurse')
                            {
                                RtIdRegNrsewP = recordType.get('Registered Nurse with Patients').getRecordTypeId();
                                RecNameRegNrsewP=recordType.get('Registered Nurse with Patients').getName();
                            }
                            else
                            {
                                RtIdSpchTrpwP = recordType.get('Speech Therapy with Patients').getRecordTypeId();
                                RecNameSpchTrpwP=recordType.get('Speech Therapy with Patients').getName();
                            }

                    
                    
                            for(Opportunity oppty:opty)
                            {
                                extid=Integer.valueOf(oppty.Opty_No__c)+1;
                            }
                    
                       
                           
                             Opportunity newopp =new Opportunity();
                             newopp.Optycreationbatch__c='DVA-WP-'+myeffDate+'-'+extid;
                             
                             
                                 for(Rate_Card__c rc : rcardnewlist)
                            {
                                    OpportunityLineItem oli = new OpportunityLineItem();
                                     oli.Opportunity =new Opportunity(Optycreationbatch__c=newopp.Optycreationbatch__c);
                                    oli.PriceBookEntryId = rc.PricebookEntryId__c;
                                    oli.Patient_Service__c=pslines.Id;
                                    oli.Provider_Name__c=pslines.Resource_Name__c;
                                    oli.Patient_Service_Invoice_Start__c=pslines.Patient_Service_Invoice_Start__c;
                                    oli.Patient_Service_Invoice_Finish__c=pslines.Patient_Service_Invoice_Finish__c;
                                    oli.Rate_Card__c=rc.Id;
                                    oli.UnitPrice = rc.Hourly_Rate__c;
                                    oli.Quantity = pslines.Job_allocation_count__c;
                                    oli.Patient_Service_Lunch__c=pslines.Patient_Service_Lunch__c;
                                    oli.Invoice_Start__c=pslines.Job_Invoice_Start__c;
                                    oli.Invoice_Finish__c=pslines.Job_Invoice_Finish__c;
                                    oli.Lunch_Break_Duration_from_Job__c=pslines.Lunch_Break_Duration_from_Job__c;
                                    oli.DVA_Code__c=pslines.DVA_Code__c;
                                    oli.AHP_Type__c=pslines.Podiatry_Services__c;
                                    
                                     if(pslines.Job_Billable__c ==true)
                                         {
                                              oli.Job_lkup__c=pslines.Job__c;
                                               oli.UnitPrice = rc.Footwear_Dispensed__c;
                                                oli.Quantity = pslines.Job_allocation_count__c;
                                         
                                         }
                                         else
                                             {
                                                oli.Job_lkup__c=pslines.Job__c;
                                                oli.Quantity = pslines.Job_Invoice_Duration__c; 
                                                oli.UnitPrice=0;
                                             }
                                             
                                        if( (oli.Quantity!=NULL) && (oli.PriceBookEntryId!=NULL))
                                            {
                                             olilist1.add(oli);
                                             psupdlist.add(pslines);
                                            }
                            
                            
                            
                                    newopp.OwnerId=vLstUserop.Id;
                                      newopp.stagename='To be reviewed';
                                      Nxtoptycreationdate=rc.Next_Opportunity_Creation_Date__c;
                                      Closedate=rc.Next_Billable_Date__c;
                                      BillableCycle=rc.Opportunity_Creation_Frequency__c;
                                      InvoiceSentby=rc.Invoice_sent_by__c;
                                      InvoiceSentTo=rc.Invoice_sent_to__c;
                                      Accntterms=rc.Account_Terms__c;
                                      RateCardtype=rc.Rate_Card_Type__c;
                                    
                                          newopp.DVA__c = true;
                                        newopp.AccountId=pslines.Patient__r.DVA_Account__c;
                                    
                                            System.debug('$$$$$$$$$$$$$$$$$$$$$$$$'+pslines.Patient__r.DVA_Account__r.Name);
                                            if(pslines.RecordType.name =='Podiatry')
                                            {
                                            newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePodwP + '-'+ Nxtoptycreationdate.format();
                                            newopp.RecordTypeId = recordType.get('Podiatry with Patients').getRecordTypeId();
                                            }
                                            else if(pslines.RecordType.name =='Audiology')
                                            {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameAudwP + '-'+ Nxtoptycreationdate.format();
                                                     newopp.RecordTypeId=RtIdAudwP ;
                                             }
                                           else if(pslines.RecordType.name =='Dietetics')
                                            { 
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameDiteticscwP + '-'+ Nxtoptycreationdate.format();
                                                       newopp.RecordTypeId=RtIdDiteticscwP ;
                                             }
                                           else if(pslines.RecordType.name =='Diversional Therapy')
                                            {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameDivTrpwP + '-'+ Nxtoptycreationdate.format();
                                                     newopp.RecordTypeId=RtIdDivTrpwP ;
                                             }
                                           else if(pslines.RecordType.name =='Mental Health')
                                            {
                                                    newopp.RecordTypeId=RtIdMntHlthwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameMntHlthwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Occupational Therapy')
                                            {
                                                    newopp.RecordTypeId=RtIdOccTrpwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameOccTrpwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Optometry')
                                            {
                                                    newopp.RecordTypeId=RtIdOptmwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameOptmwP + '-'+ Nxtoptycreationdate.format();
                                             }
                                           else if(pslines.RecordType.name =='Physiotherapy')
                                            {
                                                    newopp.RecordTypeId=RtIdPhytrpwP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePhytrpwP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Physiotherapy Exercise Classes')
                                            {
                                                    newopp.RecordTypeId=RtIdPhyTrpExClswP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNamePhyTrpExClswP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Registered Nurse')
                                            {
                                                    newopp.RecordTypeId=RtIdRegNrsewP ;
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameRegNrsewP + '-'+ Nxtoptycreationdate.format();
                                            }
                                           else if(pslines.RecordType.name =='Speech Pathology')
                                                    {
                                                    newopp.Name= pslines.Patient__r.DVA_Account__r.Name +'-' + RecNameSpchTrpwP + '-'+ Nxtoptycreationdate.format();
                                                      newopp.RecordTypeId=RtIdSpchTrpwP ; 
                                                     }
                                                      
                                      newopp.closedate=Closedate;
                                      newopp.Billable_Cycle__c=BillableCycle;
                                      newopp.RateCard__c=rc.Id;
                                      newopp.Invoice_sent_by__c=InvoiceSentby;
                                      newopp.Invoice_sent_to__c=InvoiceSentTo;
                                      newopp.Date_From__c=pslines.Job_Start_Datew_otime__c;
                                      newopp.Patient_DVA_No__c = pslines.Patient_DVA_Number__c;
                                      newopp.Patient_Medicare_No__c = pslines.Patient_Medicare_No__c;
                                      newopp.AHP_Type__c= pslines.Podiatry_Services__c;
                                      newopp.Date_To__c=Nxtoptycreationdate;
                                      newopp.Service_Type__c=RateCardtype;
                                      oplist.add(newopp);
                                    
                                
                                }
                    }                               
                        
                    }   
                
                }        
          if(olilist1.size()>0 && oplist.size()>0)
                   {
                  
                Database.SaveResult[] srList = Database.insert(oplist,false);
                Database.SaveResult[] srListlineitem = Database.insert(olilist1,false);  
                List<OpportunityLineItem> psidsfromlines=new List<OpportunityLineItem>();
                List<Patient_Services__c> psfinalupd= new List<Patient_Services__c>();
                List<Patient_Services__c> pswthsamejob = new List<Patient_Services__c>();
                List<sked__Job__c> jobfinalupd=new List<sked__Job__c>();
                Map<Id,Boolean> lineidssuccess=new Map<Id,Boolean>();
                List<Billing_Error_log__c> errorlog=new List<Billing_Error_log__c>();
                
                 for (Database.SaveResult sr : srListlineitem) 
                {
                        if (!sr.isSuccess()) 
                        {
                          Billing_Error_log__c billlog = new Billing_Error_log__c();
                                       
                            for(Database.Error err : sr.getErrors()) 
                            {
                              billlog.Error_Message__c='The following error has occured while inserting Line items:'+err.getStatusCode() + ': ' + err.getMessage();
                              billlog.Error_Message__c=billlog.Error_Message__c+'Line item Fields that affected this error: ' + err.getFields();
                              billlog.Object_name__c='Opportunity Product';
                              errorlog.add(billlog);
                              //insert billlog;
                            }
                        }
                    
                         if (sr.isSuccess()) 
                        {
                             lineidssuccess.put(sr.getId(),sr.isSuccess());
                        }
                }
                  for (Database.SaveResult sr : srList) 
                {
                   if (!sr.isSuccess()) 
                    {
                    Billing_Error_log__c billlog = new Billing_Error_log__c();
                        // Operation failed, so get all errors              
                        for(Database.Error err : sr.getErrors()) 
                        {
                        
                          billlog.Error_Message__c='The following error has occured while inserting opportunity:'+err.getStatusCode() + ': ' + err.getMessage();
                          billlog.Error_Message__c=billlog.Error_Message__c+' Opportunity Fields that affected this error: ' + err.getFields();
                          billlog.Object_name__c='Opportunity';
                          //if(billlog.Id=='')
                          errorlog.add(billlog);
                          //insert billlog;
                        }   
                    }                    
                                        
                } 
        system.debug('errorlog'+errorlog);
        if(errorlog.size()>0)
        {
        insert errorlog;
        }
        
        
                if(lineidssuccess.size()>0)
            {
                    psidsfromlines=[select Id,Patient_Service__c from OpportunityLineItem where Id in: lineidssuccess.keySet()];
                    List<sked__Job__c> jobvalues;
                    List<Patient_Services__c> psvalues;
                    Map<Id,Id> psidmap=new Map<Id,Id>();
                    Map<Id,String> jobidmap=new Map<Id,String>();
                    Integer counterjob=0;
                    if(psidsfromlines.size()>0)
                {
                    for(OpportunityLineItem oitem:psidsfromlines)
                        {
                            psidmap.put(oitem.Id,oitem.Patient_Service__c);
                        }
                  
                    try
                    {
                          psvalues=[select Id, Added_to_Opty__c,Dispensing_Footwear_F049__c,Added_to_Opty_Dispensing_Footwear__c from Patient_Services__c where Id in :psidmap.values()];
                          system.debug('psvalues'+psvalues);
                              for(Patient_Services__c psupdt:psvalues)
                              {                 
                                  psupdt.Added_to_Opty_Dispensing_Footwear__c=true;   
                                  psfinalupd.add(psupdt);
                              }
                         
                         if(psfinalupd.size()>0)
                        {
                         system.debug('psfinalupd'+psfinalupd);
                         update psfinalupd;
                         }
                    }
                    
                    catch(DMLException e)
                    {
                        list<string> emailsjob = new list<string>();
                        Messaging.reserveSingleEmailCapacity(2);
                        Messaging.SingleEmailMessage mailjob = new Messaging.SingleEmailMessage();
                                        htmlBody += 'Dear Admin,';
                                        htmlBody += '<br/><br/>DML Exception Occurred: e.getMessage()';
                                        htmlBody += '<br/><br/>Error Message: ' + e.getMessage() + '. Error Message: e.getMessage()';
                                        htmlBody += '<br/><br/>Regards,<br/><br/>HealthStrong Salesforce Admin</p>';
                                        htmlBody += '</td></tr></table></td></tr></table></td><td width="3" style="background-color:transparent;background-image:url(http://i3.createsend1.com/ti/r/F2/A34/58B/075043/images/main_right.png);background-repeat:repeat-y;background-position:0 0;background-attachment:scroll;" ></td></tr></table> </td></tr></table></body></html>';
                        mailjob.setHtmlBody(htmlBody);
                        emailsjob.add('errorlog@healthstrong.com.au');
                        mailjob.setToAddresses(emailsjob);
                        mailjob.setSaveAsActivity(false); 
                         mailjob.setReplyTo('technicalsupport@healthstrong.com.au');
                        mailjob.setSenderDisplayName('HealthStrong Salesforce Support');
                       mailjob.setSubject('Error Updating the flag Added to Opportunity for the Jobs');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mailjob });
                    }
                 }
            }
           }
                   
         }

    }
due to size limitation i will give by code in below post
Amol ChAmol Ch
Here is the test class
@Istest(SeeAllData=false)
public class CreateOptyTest123 {
    Static testmethod void CreateOptyTest1()
    {
        Map<String, Schema.SObjectType> sObjectMap = Schema.getGlobalDescribe() ;
        Map<String,Schema.RecordTypeInfo> recordType = sObjectMap.get('Opportunity').getDescribe().getRecordTypeInfosByName();
      
        RecordType rt = [select id,Name from RecordType where SobjectType='Patient_Services__c' and Name='Podiatry'];

     
        Id DVAAccRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('DVA Account').getRecordTypeId();                
       	ID psrtidp =  Schema.SObjectType.Patient_Services__c.getRecordTypeInfosByName().get('Podiatry').getRecordTypeId();
        ID psrtidaud =  Schema.SObjectType.Patient_Services__c.getRecordTypeInfosByName().get('Audiology').getRecordTypeId();
        ID psrtiddie =  Schema.SObjectType.Patient_Services__c.getRecordTypeInfosByName().get('Dietetics').getRecordTypeId();
          ID psrtiddivtrp =  Schema.SObjectType.Patient_Services__c.getRecordTypeInfosByName().get('Diversional Therapy').getRecordTypeId();
        String psrtnmp =  Schema.SObjectType.Patient_Services__c.getRecordTypeInfosByName().get('Podiatry').getName();
       
        List<Account> Parentacc= new List<Account>();
         Parentacc.add(new Account(RecordTypeId = DVAAccRecordTypeId, 
                                          Name = 'Department of Veteran Affairs',
                                          Account_Address__c = '123 street 123', 
                                          ABN__c = '1236523652',
                                          Email__c = 'test1@test.com', 
                                          Facility_Notification_Opt_Out__c = True,
                                          Is_Admin__c = True,
                                          Active__c = True));
      insert Parentacc;
        
         List<Contact> Con= new List<Contact>();
        Con.add(new contact(FirstName = '',
                              LastName = 'TestContact',
                              accountId = Parentacc[0].id,
                              MobilePhone = '1234567890',
                              email = 'test@skedulo.com',
                              MailingStreet = 'ABC',
                              Active__c = True,
                              MailingCity = 'ABC',
                              MailingState = 'ABC',
                              MailingPostalCode = 'ABC',
                              MailingCountry = 'ABC'));
            insert Con;
            
          Parentacc[0].Account_Contact__c = con[0].id;
          update Parentacc;
        
         List<Account>  acc= new List<Account>();
         acc.add(new Account(RecordTypeId = DVAAccRecordTypeId,         
                                    Name = 'Medicare Account',
                                    ParentId=Parentacc[0].Id,
                                    Account_Address__c = '123 street 123',
                                    ABN__c = '12345678912',
                                    Email__c = 'test@test.com',
                                    Facility_Notification_Opt_Out__c = True,
                                    Medicare_Number__c = '123456789',
                                    Is_Admin__c = True,
                                    Active__c = True,
                                    Card_Expiry_Date__c = system.today().addDays(10)));
           insert acc;
        
         sked__Region__c Reg = new sked__Region__c(Name='SYD');
         Reg.sked__Timezone__c='Australia/Sydney';
         insert Reg;
        
         sked__Location__c Loc = new sked__Location__c( Name = 'Test Location',sked__Region__c = Reg.Id,sked__Address__c = 'Test Address' );
         insert Loc;
        
         sked__Resource__c Res = new sked__Resource__c(Name = 'Test Resource', sked__User__c=UserInfo.getUserId(),sked__Primary_Region__c = Reg.Id);
         insert Res;
        
         Patient__c pat1 = new Patient__c(First_Name__c='First', Last_Name__c='Last',Medicare_Account__c=acc[0].id, Location__c=Loc.Id, Patient_Status__c='Active');
         Patient__c[] pat = new Patient__c[]{pat1};     
         insert pat;
        
        List<sked__Job__c> job=new List<sked__Job__c>();         
        job.add(new sked__Job__c(skdate__Finish__c = '20/08/2014 8:30 AM',
                                            skdate__Start__c = '18/08/2014 8:30 AM',
                                            Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM'),
                                            Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM'),
                                            sked__Duration__c = 501,
                                            sked__Region__c = Reg.Id,
                                            sked__Type__c='Podiatry Clinic',
                                            Service_Type__c='Podiatry',
                                            Job_Billable__c =true,
                                            Resource_Name__c=Res.Name));
         
         job.add(new sked__Job__c(skdate__Finish__c = '20/08/2014 8:30 AM',
                                            skdate__Start__c = '18/08/2014 8:30 AM',
                                            Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM'),
                                            Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM'),
                                            sked__Duration__c = 501,
                                            sked__Region__c = Reg.Id,
                                            sked__Type__c='Audiology Clinic',
                                 	        Service_Type__c='Audiology',
                                            Job_Billable__c =true,
                                            Resource_Name__c=Res.Name));
        
          job.add(new sked__Job__c(skdate__Finish__c = '20/08/2014 8:30 AM',
                                            skdate__Start__c = '18/08/2014 8:30 AM',
                                            Invoice_Start__c = DateTime.parse('18/08/2014 8:30 AM'),
                                            Invoice_Finish__c = DateTime.parse('20/08/2014 8:30 AM'),
                                            sked__Duration__c = 501,
                                            sked__Region__c = Reg.Id,
                                            sked__Type__c='Dietetics Clinic',
                                 	        Service_Type__c='Dietetics',
                                            Job_Billable__c =false,
                                      	Non_Billable_Reason__c='Travel',
                                            Resource_Name__c=Res.Name));  
         insert job;
        system.assertEquals('Podiatry', job[0].Service_Type__c);
        
         List<Patient_Services__c> ps= new List<Patient_Services__c>();
         ps.add(new Patient_Services__c(Service_Type__c = 'Podiatry',
                                                Patient__c = pat1.Id,
                                                Job__c = job[0].id,
                                                Who_to_Invoice__c='Medicare Account',
                                         		RecordTypeid=psrtidp,
                                                Ready_for_Billing__c=true,
                                                Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM'),
                                                Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM'),
                                                Patient_Service_Lunch__c='10'));
         ps.add(new Patient_Services__c(Service_Type__c = 'Audiology',
                                                Patient__c = pat1.Id,
                                                Job__c = job[1].id,
                                        		Ready_for_Billing__c=true,
                                                Who_to_Invoice__c='Medicare Account',
                                                RecordTypeid= psrtidaud,
                                                                   Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM'),
Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM'),
                       Patient_Service_Lunch__c='10'));
          ps.add(new Patient_Services__c(Service_Type__c = 'Dietetics',
                                                Patient__c = pat1.Id,
                                                Job__c = job[2].id,
                                        		Ready_for_Billing__c=true,
                                                Who_to_Invoice__c='Medicare Account',
                                                RecordTypeid= psrtiddie,
                                                Patient_Service_Invoice_Start__c=DateTime.parse('18/08/2014 8:30 AM'),
                                                Patient_Service_Invoice_Finish__c=DateTime.parse('20/08/2014 8:30 AM'),
                                                Patient_Service_Lunch__c='10'));
        insert ps;
        system.assertEquals('Podiatry', ps[0].Service_Type__c);
 
        Product2 prod = new Product2(Name = 'Laptop X200',Family = 'Hardware');
        insert prod;
         Id pricebookId = Test.getStandardPricebookId();
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         PricebookEntry standardPrice = new PricebookEntry(
            Pricebook2Id = pricebookId, Product2Id = prod.Id,
            UnitPrice = 10000, IsActive = true);
        insert standardPrice;
        
        PricebookEntry Pricebook = new PricebookEntry(
            Pricebook2Id = customPB.Id, Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert Pricebook;
       List<Rate_Card__c> rcard =new List<Rate_Card__c>();    
        rcard.add(new Rate_Card__c(Is_Active__c=true,
                                    Rate_Card_Type__c='Podiatry',
                                    Job_Type__c='Podiatry Clinic',
                                    Invoice_sent_by__c='Email',
                                    Invoice_sent_to__c='Account',
                              	    PricebookEntryId__c= Pricebook.id,
                                    Treatment_Rate__c=100.00,
                                    Account__c = Parentacc[0].Id,
                                    Which_Rate_to_use_withpatients__c='Always use Treatment Rate',
                                    Next_Opportunity_Creation_Date__c=date.parse('18/08/2016')));
         rcard.add(new Rate_Card__c(Is_Active__c=true,
                                    Rate_Card_Type__c='Audiology',
                                    Job_Type__c='Audiology Clinic',
                                    Invoice_sent_by__c='Email',
                                    Invoice_sent_to__c='Account',
                                    PricebookEntryId__c= Pricebook.id,
                                    Treatment_Rate__c=100.00,
                                    Account__c = Parentacc[0].Id,
                                    Which_Rate_to_use_withpatients__c='Always use Treatment Rate',
                                    Next_Opportunity_Creation_Date__c=date.parse('18/08/2016')));
        
        rcard.add(new Rate_Card__c(Is_Active__c=true,
                                    Rate_Card_Type__c='Dietetics',
                                    Job_Type__c='Dietetics Clinic',
                                    Invoice_sent_by__c='Email',
                                    Invoice_sent_to__c='Account',
                                    PricebookEntryId__c= Pricebook.id,
                                    Treatment_Rate__c=100.00,
                                    Account__c = Parentacc[0].Id,
                                    Which_Rate_to_use_withpatients__c='Always use Treatment Rate',
                                   Next_Opportunity_Creation_Date__c=date.parse('18/08/2016')
                                      ));
        
         insert rcard;
      
        test.startTest();
        ps[0].Dispensing_Footwear_F049__c=true;
       update ps;
        ps[1].Dispensing_Footwear_F049__c=true;
       update ps;
  		 ps[2].Dispensing_Footwear_F049__c=true;
        update ps;
        test.stopTest();
when we update in seperate as 
test.startTest();
ps[0].Dispensing_Footwear_F049__c=true; 
update ps;
ps[1].Dispensing_Footwear_F049__c=true; 
update ps; 
ps[2].Dispensing_Footwear_F049__c=true; 
update ps; 
test.stopTest();
it gives me 62 % code coverage and try to again add in seperate way it gives me error too many soql query
when i try to update in mass like
test.startTest();
ps[0].Dispensing_Footwear_F049__c=true; 
ps[1].Dispensing_Footwear_F049__c=true; 
ps[2].Dispensing_Footwear_F049__c=true; 
update ps; 
test.stopTest();
it gives me error
System.DmlException: Update failed. First exception on row 0 with id a0nO0000003gshtIAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CreateOpporty: execution of AfterUpdate
caused by: System.ListException: Before Insert or Upsert list must not have two identically equal elements
Class.OptyCreationForDispFootPres.createopty: line   Database.SaveResult[] srList = Database.insert(oplist,false);

Please guide how to cover code coverage 
 
N.M. SharmaN.M. Sharma
 Hi Amol,
I have made some changes,
ps[0].Dispensing_Footwear_F049__c=true;
update ps[0];
ps[1].Dispensing_Footwear_F049__c=true;
update ps[1];
ps[2].Dispensing_Footwear_F049__c=true;
update ps[2];

Try this. Every time you just change a single record value and update the whole list. Try to change all the element and Update once. Hopefully it will work.

 
Amol ChAmol Ch
Hi N.M.

This will work but it gives me only 62 % of code coverage, to incerase code coverage i've to cover remaining conditon; for that when i add agin test data and try to update in same way 4th time it gives me too many soql query
N.M. SharmaN.M. Sharma
Hi Amol,

I think you want to cover the catch part am i right?
For cover this Just miss any required filed in your flow and perform DML on it. The exception case automatically cover your catch part.

Thanks 
Amol ChAmol Ch
Hi N.M.

In my test class, i've cover line no 339 of apex class,  but dev console showing  line no 348 to 388of apex class in red color means its not cover. I'm not sure why ? it might increase my code coverage can you help me for this. where is the problem or what i need to add
and another is in my apex class their is else if condition means this is for different records, how can i cover this in test class.
can we update in mass in test class?, if we can then why it throwing it above error as i mention. Is problem in my test class or my apex class. i'm not sure....
Please guide me
 
N.M. SharmaN.M. Sharma
Hey,

i am assuming that you miss to insert the OpportunityLineItem for cover the test code coverage
First insert the LineItem and then let me know is it working or not.

Thanks
Is my ans is meaningfull for you please mark as solution :)