+ Start a Discussion
karthikeya 2karthikeya 2 

Test class code coverage Needed....

Hi All,
How to write test method for following code, please help me.

public class UpdateContactController {
public class MyWrapper
    {
      public string BenifitPlan1{get; set;}
      public Integer PersonnelNumber1 {get; set;}
      public Integer PlanNumber1 {get; set;}
      public string DependentPlan1 {get; set;}
      
      public MyWrapper(Integer PersonnelNumber,string BenifitPlan,string DependentPlan,Integer PlanNumber )  //
      {
          
          PersonnelNumber1 = PersonnelNumber;
          BenifitPlan1 = BenifitPlan;
          DependentPlan1 = DependentPlan;
          PlanNumber1 = PlanNumber;
          
      }
    }
}

Thanks in Advance
Best Answer chosen by karthikeya 2
scottbcovertscottbcovert
Hi Karthikeya,

I'd highly recommend checking out Trailhead and this introduction to test code coverage for Apex: https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Here is some sample code to get you started:
 
@IsTest(seealldata=false)
public with sharing class TestClass { 
    
    public static void testUpdateContactController() {
        
        String benefitPlanValue = 'benefit';
        Integer personnelNumberValue = 1;
        Integer planNumberValue = 2;
        String dependentPlanValue = 'dependent';

        UpdateContactController.MyWrapper testWrapper = new UpdateContactController.MyWrapper(benefitPlanValue,personnelNumberValue,planNumberValue,dependentPlanValue);
        
        // Assertions
        System.assertEquals(benefitPlanValue,testWrapper.BenefitPlan1,'Benefit plan value not set properly!');
        System.assertEquals(personnelNumberValue,testWrapper.PersonnelNumber1,'Personnel number value not set properly!');
        System.assertEquals(planNumberValue,testWrapper.PlanNumber1,'Plan number value not set properly!');
        System.assertEquals(dependentPlanValue,testWrapper.DependentPlan1,'Dependent plan value not set properly!');

    }

}

 

All Answers

scottbcovertscottbcovert
Hi Karthikeya,

I'd highly recommend checking out Trailhead and this introduction to test code coverage for Apex: https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Here is some sample code to get you started:
 
@IsTest(seealldata=false)
public with sharing class TestClass { 
    
    public static void testUpdateContactController() {
        
        String benefitPlanValue = 'benefit';
        Integer personnelNumberValue = 1;
        Integer planNumberValue = 2;
        String dependentPlanValue = 'dependent';

        UpdateContactController.MyWrapper testWrapper = new UpdateContactController.MyWrapper(benefitPlanValue,personnelNumberValue,planNumberValue,dependentPlanValue);
        
        // Assertions
        System.assertEquals(benefitPlanValue,testWrapper.BenefitPlan1,'Benefit plan value not set properly!');
        System.assertEquals(personnelNumberValue,testWrapper.PersonnelNumber1,'Personnel number value not set properly!');
        System.assertEquals(planNumberValue,testWrapper.PlanNumber1,'Plan number value not set properly!');
        System.assertEquals(dependentPlanValue,testWrapper.DependentPlan1,'Dependent plan value not set properly!');

    }

}

 
This was selected as the best answer
karthikeya 2karthikeya 2
Hi 
this is actualclass, after keeping above code in test class, code coverage went down. previous it is 15%.

public class UpdateContactController {

    public integer totalsuccessrec { get; set; }
    public integer totalrecords { get; set; }
    Public string Error { get; set; }
    
    public integer totalunsuccessrec { get; set; }
    public integer totalsuccessreccount { get; set; }
    
    public String nameFile { get; set; }
    
    public list<contact> lcon = new list<contact> ();
    transient public list<id> listids= new list<id>();
    public integer size{get; set;}
    
    public static final id candRecTypeId = WCT_Util.getRecordTypeIdByLabel('Contact','Employee');

    public List<MyWrapper> wrapper {get; set;}
    public boolean b {get{
        if(wrapper!=null)
          {
          return wrapper.size()>0?true:false;
          }
          else 
          {
          return false;
          }
    }
    }
    
    transient public Map<string, contact> conNamesIdMap = new Map<string, contact>();
    transient public Blob contentFile { get; set; }
    String[] filelines = new String[]{};
    List<Contact> Conlist;
    public Contact UpdateCon;
    List<integer> conNames;
    Set<String> conNamesf;
    Set<String> conNamesr;
    public  list<string> num = new list<string> (); 
    Map<Integer, Contact> newlistmap = new Map<Integer, Contact>();
    List<Contact> newCons = new List<Contact>();
    
    string stri;
    
    public PageReference ReadFile() {
        Error = 'Personal Number does not exists';
        
        conNamesIdMap =new Map<string, contact>();
        //system.debug('abc............1');
        /*Validtion if no file selected */
        //---------------------------------------------------------------------------------------------------
        //Taking file extension.
        String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        
        if(extension != 'csv' ||extension != 'CSV')
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'The file must be in comma delimited format (.csv). Please upload an appropriate file format.');
            ApexPages.addMessage(errormsg);
            return null;
        }
        
        // IF uploaed file is emplty
        if(contentFile!=null)
        {
            nameFile =contentFile.toString();
            //system.debug('abc............3');
        }
        else
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Please choose a file to upload !'));
            //system.debug('abc............3 a');
            return null;
        }
        filelines = nameFile.split('\n');
        Conlist= new List<Contact>();
        conNames = new List<integer>();
        conNamesf = new set<String>();
        conNamesr= new set<String>();
        wrapper = new List<MyWrapper>() ;
        listids= new list<id>();
        newlistmap= new Map<Integer, Contact>();
        totalunsuccessrec =0;
        totalsuccessrec =0;
        totalrecords=0;
        totalsuccessreccount=0;
        system.debug('Debug Line 1: ');
        /*Step 1 :: Processing the uploaded file and fetching the various details into  the contact object List newlistmap.*/   
        //system.debug('abc............4');    
        for (Integer i=1;i<filelines.size();i++)
        {
            //system.debug('abc............5');
            totalrecords++;
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            Contact c = new Contact();
            
            system.debug('output vaues****');
            if(inputvalues[0]!=null?inputvalues[0].trim()!='':false)
            {
                //system.debug('abc............6');
                c.WCT_Personnel_Number__c = integer.valueOf(inputvalues[0]!=null?inputvalues[0].trim():inputvalues[0]);
            }
            
            c.WCT_Benefit_plan__c = inputvalues[1];
            c.Dependent__c = inputvalues[2];
            
            if(inputvalues[3]!=null?inputvalues[3].trim()!='':false)
            {
                c.Plan_Num__c=integer.valueOf(inputvalues[3]!=null?inputvalues[3].trim():inputvalues[3]);   
            }
            
            if (c.WCT_Personnel_Number__c > 0 )
            {
                conNames.add(integer.valueOf(c.WCT_Personnel_Number__c));   
                newlistmap.put(integer.valueOf(c.WCT_Personnel_Number__c),c);
            }
            
            if(c.WCT_Personnel_Number__c > 0){
                //system.debug('abc............9');
                Conlist.add(c);
            }
            
        }
        
        //create a map with names as key
        // load the map - this will help you find out if an Contact name exists already
        /*Step 2 : Searching for the contacts with the emails ids from the Uploaded file in the SFDC. 
        */
        
        List<Contact> existingConts = [SELECT Id,FirstName,LastName,Email,Plan_Num__c,Dependent__c,WCT_Personnel_Number__c,WCT_Benefit_plan__c,WCT_Insurance_Benefits__c FROM Contact where WCT_Personnel_Number__c IN :conNames  limit 5000];
        
        /*Step 3 : By this step 'existingConts' has contacts record present in SFDC. 
                  A. Now, Modifying the existing contacts (existingConts) with new values from 'newlistmap' (from uploaded file)
                  B. At the same time remove the record which are been existing from the 'newlistmap' */
        
        for (Contact cont: existingConts)
        {
            If(newlistmap.containsKey(integer.valueOf(cont.WCT_Personnel_Number__c)))
            {
              UpdateCon = newlistmap.get(integer.valueOf(cont.WCT_Personnel_Number__c));
              //system.debug('UpdateCon*********'+UpdateCon);
               if(UpdateCon.WCT_Benefit_plan__c!=null ){
                  Cont.WCT_Benefit_plan__c=UpdateCon.WCT_Benefit_plan__c;
                }
                else{
                    Cont.WCT_Benefit_plan__c=UpdateCon.WCT_Benefit_plan__c;
                }
                
                if(UpdateCon.Plan_Num__c!=null ){
                  Cont.Plan_Num__c=UpdateCon.Plan_Num__c;
                }
                else{
                    Cont.Plan_Num__c=UpdateCon.Plan_Num__c;
                }
                
                if(UpdateCon.Dependent__c!=null && UpdateCon.Dependent__c!= ''){
                  Cont.Dependent__c=UpdateCon.Dependent__c;
                  Cont.WCT_Insurance_Benefits__c = true;
                }
                else{
                    Cont.Dependent__c=UpdateCon.Dependent__c;
                    Cont.WCT_Insurance_Benefits__c = false;
                }
                
              
        /*Step 3 B : Deleting the Contact of the existing contact from the newlistmap. By this at the end of this loop, newlistmap will contain only the contact not present in the SFDC.*/
            newlistmap.remove(integer.valueOf(cont.WCT_Personnel_Number__c));
            }
        }
        
        /*Step 4 : Now 'existingConts' has contacts record present in SFDC with modified values from the uploaded files. Now update these contact into SFDC.*/
           if(existingConts.size()>0)
           {
            Update existingConts;
           }
        /*Step 5 : Generating the report for End User.
         *        1. Records do not exist : Size of newlistmap. Hint :: Since all existing records are been removed from newlistmap.
         *        2. Records successfully updated : 'totalrecords' (total records in Uploaded file) - (Records do not exist).
         *        3. Update the wrapper class with non existing contact details.
        */
        
        totalunsuccessrec=newlistmap.size();
        totalsuccessreccount=existingConts.size();
        Set<integer> numbers=newlistmap.keySet();
        //list<integer> numbers=newlistmap.keySet();
        system.debug('numbers**********'+numbers);
        for(Integer int1: numbers)
        {
            Contact c=newlistmap.get(int1);
             wrapper.add(new MyWrapper(integer.valueOf(c.WCT_Personnel_Number__c),c.Dependent__c,c.WCT_Benefit_plan__c,integer.valueOf(c.Plan_Num__c)));
              
           
        }
        
        try
         {
         for(string s:conNamesr)
         {
            if(conNamesf.contains(s))
            {
              conNamesf.remove(s);     
            }
         }

        // Update Cont;
        /* ApexPages.Message msg = new ApexPages.Message(ApexPages.severity.info,'ContactName with Contact Id are the new contact created.Related Contact and Opportunity also created');
         ApexPages.Message msg1 = new ApexPages.Message(ApexPages.severity.info,'ContactName without Contact Id are the existing Contacts');
         ApexPages.addMessage(msg);
         ApexPages.addMessage(msg1);*/

        }
        
        catch (Exception e)
        {

        ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Contact Personal Number already exist, change Contact Personal Number and try again');
        ApexPages.addMessage(errormsg);
        }
        return null;
    }
    
    public List<Contact> getuploadedAccounts()
    {
     list<contact> lcon1;
        if (Conlist!= NULL)
        
            if (Conlist.size() > 0){
                conlist.clear();
                return conlist;
            }
               
            else
             return null;               
            else
            return null;
    }  
    
    public PageReference pg() {
       return page.UpdateContactUI;
    }
    
    public class MyWrapper
    {
      public string BenifitPlan1{get; set;}
      public Integer PersonnelNumber1 {get; set;}
      public Integer PlanNumber1 {get; set;}
      public string DependentPlan1 {get; set;}
      
      public MyWrapper(Integer PersonnelNumber,string BenifitPlan,string DependentPlan,Integer PlanNumber )  //
      {
          
          PersonnelNumber1 = PersonnelNumber;
          BenifitPlan1 = BenifitPlan;
          DependentPlan1 = DependentPlan;
          PlanNumber1 = PlanNumber;
          
      }
    }
}

please help to write code, Thanks in Advance.
scottbcovertscottbcovert
HI Karthikeya,

In order to raise your code coverage you'll want to read through the documentation on writing Apex test classes:

https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

Essentially you're writing code to run through all the use cases that your users might implement while they use your application, VFPage, etc. to verify that your code has no run-time errors and executes as expected/desired.