+ Start a Discussion
john dsouzajohn dsouza 

How to write a test class with test methods for code given

I have two custom objects fan and preferences.
IN fan object I have email,birthdate field and in preference sobject I have a multi select picklist wihich has a default value as ''ALTERNATIVE / INDIE'.

Preference object has a lookup to Fan object.

The email field(mandatory) is masked with asterisk, so when the page loads the code masks the contents and when the user clicks save button page is refreshed and email field value is masked.

Also when the page loads I  append an ID to the url to fetch the values.
Here is a piece of code .
public class PrefCenterCtrl{
      
    public String fanDOB { get; set; }
    public String fanCountry_Region { get; set; }
    public String fanEmail { get; set; } 
    public String fan_email{get;set;}  

     public String encryptedfanID{get;set;}
    
    public String mid{get;set;}
    
    public fan__c fan{get;set;}
      
    public Preference__c pref;
    public boolean Genre_Alternative_Indie { set; get; }

    private List<SelectOption> countryCodeList = new List<SelectOption>();

     public PrefCenterCTRL()
    {
        encryptedfanID='';
        mid='';
        
        encryptedfanID=ApexPages.currentpage().getparameters().get('id');
               
        if(String.isBlank(encryptedfanID))
        {
                ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: Invalid Id.');
                ApexPages.addMessage(myMsg);
                return;
        }
        else
        {
          try
          {
            fetchfanvalues();
          }
          catch(System.QueryException ex){
                
              Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, 'No Record'));
          }
   
        }}
       
 public void fetchfanvalues()
    {
         fan = new fan__c();
         
         fan=[SELECT id, Email__c,Birthdate__c,Country_Region__c
              FROM fan__c 
              WHERE Encrypted_ID__c=:encryptedfanID];
         
         if (fan != NULL)
         {
                        
             fan_email=fan.Email__c;
             
             if(fan_email != null && fan_email != '' )
             {
                fanEmail=maskEmail(fan_email);
             }
             else
             {
                 fan_Email = fan.Email__c;
             }}

          pref=new Preference__c();
        
       try
       {
        pref = [SELECT Preferred_Genre__c
                      FROM Preference__c
                      WHERE Fan_Id__c = :fan.Id];
    //Preferred_Genre__c is defined as Multiselect Picklist in Preference object   
    String Pref_Genre = pref.Preferred_Genre__c;  
       
       if(Pref_Genre != null)
       {
             string[] Genres = pref_Genre.split(';');
                    
             for(integer G=0; G<=Genres.size()-1; G++)
             {
                            
                            if(Genres[G] == 'ALTERNATIVE / INDIE')
                                Genre_Alternative_Indie = true;
            }

        }               
           
        catch(system.Exception ex)
        {
          
        }
     }

//code to mask the email with asterisk when the page loads and also when the user clicks save button the email field content is masked with asterisk
  private String maskEmail(String sEmail)
    {   String sMaskedEmail;      
        String[] aEmail = sEmail.split('@');   
        if(aEmail.size() == 2)
        {      
          sMaskedEmail = aEmail[0].left(1); 
          for(integer i=0; i < aEmail[0].length() - 1; i++)
          {
            sMaskedEmail += '*';
          }      
          String[] aEmail2 = aEmail[1].split('\\.', 2); 
          sMaskedEmail += '@' + aEmail2[0].left(1);  
          for(integer i=0; i < aEmail2[0].length() - 1; i++)
          { 
            sMaskedEmail += '*';
          }   
          sMaskedEmail += '.' + aEmail2[1];  
        } 
          return sMaskedEmail; 
    }

//The country along with its codes is stored in custom setting
  public  List<SelectOption> getCountryCodes() 
   {
        if(countryCodeList.isEmpty())
        {
           
          for(Countries__c country :Countries__c.getAll().values())
          {

            countryCodeList.add(new SelectOption(country.CountryCode__c, country.Name));
          }

        }

        countryCodeList.sort();
        return countryCodeList;
   }

public void LoadMaskedValues()
   {
       fan = new fan__c();
       
       if (fan != NULL)
       {
      
           fan=[SELECT id, Email__c,Mobile_Phone__c
                       FROM fan__c 
                       WHERE Encrypted_ID__c=:encryptedfanID];
                       
           if(!string.isBlank(fan.Email__c))
           {
                fan_email=fan.Email__c;
                fanEmail=maskEmail(fan.Email__c);
           }
}
 
 public void SaveValues()
 {
     if (fan != NULL)
      {
      
      if(!fanEmail.contains('*'))
      {     
            integer count = [SELECT Count() FROM Fan__c WHERE Email__c =:fanEmail];
            if(count > 0)
            {
                Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, 'This Fan Already Exists In The System'));
                return;
            }
             else if(string.isEmpty(fanEmail))
            {
               ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Email Cannot Be Blank')); 
               return;
            
            }
            else if(!Pattern.matches('([a-zA-Z0-9_\\-\\.]+)@((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})', fanEmail))
            {
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Invalid Email')); 
              return;
            }
            else
            {
              fan.Email__c = fanEmail;
            }
       }
      if(!string.isBlank(fanDOB))
      {
       fan.Birthdate__c=Date.parse(fanDOB); 
      }

   try
      {
         upsert fan;
      }
      catch(System.DmlException ex)
      {
            
        Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, 'Cannot Update the Record.'+ex.getMessage()));
      }
     }   
     
     LoadMaskedValues();         
}    

public void SavePreferences()
    {    
    
    if (pref != NULL)
    {
        string Preferred_Genre = '';
        
        if(Genre_Alternative_Indie == true){
            
            Preferred_Genre += 'ALTERNATIVE / INDIE ;';
        }      

       try{
            
                pref.Preferred_Genre__c = Preferred_Genre;
                pref.fan_id__c = fan.Id;
                
                upsert pref;
                    
        }catch(System.DMLException ex){
            
            Apexpages.addMessage(new Apexpages.Message(Apexpages.Severity.ERROR, ex.getMessage()));
        }
      }}

 public PageReference btn_profile_saveChanges()
    {
        SaveValues();
        return null;
    }
    
    
    public void btn_preferences_saveChanges()
    {
      SavePreferences();    
    }

Please help me in writing a test class with 100% code coverage.

Thanks
John
ManojjenaManojjena
HI John,

Please start writting test class and  let us know where you have issue so that we can help you .
 
@isTest
Private class PrefCenterCtrlTest{

    private static testMethod void unitTest(){
       //Here create records 
        fan__c fn=new fan__c();
            fn.Email__c='test@gmail.com';
            fn.Birthdate__c=System.today().addDays(-600);
            fn.Country_Region__c='India'; //If pick list the give appropriate value
            insert fn ;
           ApexPages.currentpage().getparameters().put('id',fn.Id);
           PrefCenterCtrl ctrl=new PrefCenterCtrl();

            //Call Methods 

    }
}


Check below link for help !!
http://manojjena20.blogspot.in/2015/06/tips-and-tricks-for-test-class.html

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm


Thanks
Manoj
john dsouzajohn dsouza
Hi Manoj
From your code Line 14, call methods, I am not very clear on this.

like wise can u pls elaborate and how to save Preference object value?

Thanks
John