-1

I'm New to the salesforce,I have written a code which does insert cases, insert case comments, and also retrieves the list of contacts,cases,2 custom objects. Please help me how can I write test method for the below code.

public with sharing class contact_list_controller {

//variable Initialization 

  // URL parameter variables
  public String user_contact_EmailID{get; set;}
  public String contact_guid{get; set;}

  //variable for storing the date retrived from the Database
  public List<Contact> contacts;
  public List<Case> cases;
  public List<dftly_user_device__c> userdevice;
  public List<aggregateResult> results;
  private Contact contactid;
  public String Case_ID;

  // flags for internal popup
  public boolean displayPopup {get;set;}
  public boolean case_comment_popup {get; set;}

  // variable for submitting the data into the salesforce Database
  public Case newcases {get; set;} 
  public Case detailscase {get;set;}
  public CaseComment case_comment {get; set;}


// Retriving the details for the standard Object (contact) 

  public contact_list_controller(ApexPages.StandardController controller) {
     contact_guid = ApexPages.currentPage().getParameters().get('guid') ;
     user_contact_EmailID = ApexPages.currentPage().getParameters().get('contid');
     contacts = [Select ID,name,phone,mobilephone,fax,email,birthdate,mailingcity,mailingstate,mailingcountry,homephone,PhotoUrl,Lastname from contact where email = :user_contact_EmailID];
     newcases = new Case();
     case_comment = new CaseComment(); 
     detailscase = new Case();  
  }

 // Functions for Closing the popup inside the chatpopup page

  // function to close the popup    
  public void ClosePopup(){
    displayPopup=false;
  } 
  //function to close casecomment
  public void Casecomment_close(){
    case_comment_popup = false;
  }

  // function to show the popup    
  public void showPopup() {        
    displayPopup = true;     
  }  

  public void casecomment(){
    case_comment_popup = true;   
  }         

  // function for storing the Contact details in contacts variable

  public List<Contact> getContacts() {
    return contacts;
  }

  // Code for retriving the details of the Cases and checking the accessible for the user  

  public List<Case> getCases(){
      cases = null ;
      String [] caseUpdateFields = new String [] {'casenumber','Description','isclosed','priority','status','subject','type','reason','origin','CreatedDate'};
      String SFDobject = 'Case';
      // Obtaining the field name/token map for the case object
         // Obtaining the field name/token map for the case object
        if (!Schema.sObjectType.Case.isAccessible() ) {
              System.debug(LoggingLevel.Error, 'you don\'t have access to create Case');
              return null;
        }else if (FLSpermessionisAccessible(SFDobject,caseUpdateFields)){
              cases=[Select casenumber,Description,isclosed,priority,status,subject,type,reason,origin,CreatedDate from Case where case.contactid =: contacts[0].ID ORDER BY casenumber DESC limit 5]; 
               return cases;
        }else {
           System.debug(LoggingLevel.Error, 'you don\'t have access to create Case');
           return null;
        } 
  }

   // Code for retriving the details of the dftly_user_device__c and checking the accessible for the user     
  public List<dftly_user_device__c> getUserdevice() {
    if(userdevice == null){
      String [] deviceDetailUpdateFields = new String [] {'dftly__device_model__c','dftly__device_name__c','dftly__device_os__c','CreatedDate','dftly__device_platform__c','dftly__device_uuid__c','dftly__device_version__c','dftly__Device_IMEI__c'};
       String SFDobject = 'dftly__dftly_user_device__c';
      // Obtaining the field name/token map for the case object
       if (!Schema.sObjectType.dftly__dftly_user_device__c.isAccessible() ) {
        System.debug(LoggingLevel.Error, 'you don\'t have access to dftly__dftly_user_device__c');
        return null;
       } else if(FLSpermessionisAccessible(SFDobject,deviceDetailUpdateFields)){
          userdevice = [Select dftly__device_model__c,dftly__device_name__c,dftly__device_os__c,CreatedDate,dftly__device_platform__c,dftly__device_uuid__c,dftly__device_version__c,dftly__Device_IMEI__c from dftly__dftly_user_device__c where dftly__dftly_user_device__c.owned_by_contact__c =: contacts[0].ID ORDER BY CreatedDate desc limit 5];
          return userdevice;
       }else {
         System.debug(LoggingLevel.Error, 'you don\'t have access to dftly__dftly_user_device__c');
           return null;
       }
  }else {
      return null;
  } 
}

  // Function for getting the chat details form the salesforce database.

public list<AggregateResult> chatdetaillist() {
   String [] chatDetailFields = new String [] {'dftly__session_id__c','dftly__User__c','dftly__Contact__c','CreatedDate'};
   String SFDobject = 'dftly__ChatDetail__c';
   if (!Schema.sObjectType.dftly__ChatDetail__c.isAccessible() ) {
        System.debug(LoggingLevel.Error, 'you don\'t have access to dftly__ChatDetail__c');
         return null;
       } else if(FLSpermessionisAccessible(SFDobject,chatDetailFields)){
          List<aggregateResult> results = [SELECT dftly__session_id__c,dftly__User__c,MAX(CreatedDate) end,MIN(CreatedDate) start FROM dftly__ChatDetail__c chat where  chat.dftly__Contact__c =: contacts[0].ID group by dftly__session_id__c, dftly__User__c, dftly__Contact__c Order by MAX(CreatedDate) DESC limit 5];
          return results;
       }else {
         System.debug(LoggingLevel.Error, 'you don\'t have access to dftly__ChatDetail__c');
            return null;
       }
  }

  public list<AggregateResult> chatlist{
    get { return chatdetaillist(); }
  }

  public void case_detail(){
    try{
        Case_ID = Apexpages.currentPage().getParameters().get('myParam');
        String [] singleCaseDetailFields = new String [] {'casenumber','isclosed','priority','status','subject','type','reason','origin','CreatedDate'};
        string SFDobject = 'Case';
        if(Case_ID !=null && FLSpermessionisAccessible(SFDobject,singleCaseDetailFields) && Schema.sObjectType.Case.isAccessible()){
        detailscase = new Case(); 
        detailscase=[select casenumber,Description,isclosed, isdeleted,priority,status,subject,type,reason,origin,CreatedDate from case where casenumber= :Case_ID];
      }
    }
    catch (Exception ex) {
      System.debug(LoggingLevel.Error, 'contact_list_controller.case_detail() Exception: ' + ex);
    }
    finally{
      displayPopup = true;
    }
  } 

  public void Save(){
    try{
      String [] newCaseCreateFields = new String [] {'Priority','Origin','Type','Status','reason','subject','Description','ContactId'};
      newcases.contactid = contacts[0].Id; 
      if ( !Schema.sObjectType.Case.isCreateable() ) {
         System.debug(LoggingLevel.Error, 'you don\'t have access to create case');
      } else if(FLSpermessionisCreateable('Case',newCaseCreateFields)) {
          insert newcases;
      } else { 
          System.debug(LoggingLevel.Error, 'you don\'t have access to update case ContactId');
      }     
    } 
    catch (Exception ex) {
      System.debug(LoggingLevel.Error, 'contact_list_controller.Save() Exception: ' + ex);
    }
    finally{
      displayPopup=false;
    }    
}


// Function for adding the comment for each single case using the CaseID
 public void save_casecomment(){
    try{ 

          String [] newCaseCommentCreateFields = new String [] {'ParentId','CommentBody'};
          if (!Schema.sObjectType.CaseComment.isCreateable()) {
                 System.debug(LoggingLevel.Error, 'you don\'t have access to create CaseComment');
          } else if (FLSpermessionisCreateable('CaseComment',newCaseCommentCreateFields) && Schema.sObjectType.Case.isAccessible() && Schema.sObjectType.Case.fields.Id.isAccessible()) {
                 case_comment.parentid = [Select ID from Case where casenumber= :Case_ID].Id;
                 insert case_comment;
          } else {
              System.debug(LoggingLevel.Error, 'you don\'t have access to update CaseComment ParentId');    
          }     
        }
        catch (Exception ex) {
          System.debug(LoggingLevel.Error, ' save_casecomment() Exception: ' + ex);
        }
        finally{
          case_comment_popup = false;
          case_comment = new CaseComment();
        }
} 


//------------------------------------------------------------------------------------------------------------------------------------------------------
  // Changes need to be made  

  //Function for checking FLS for each object

  public boolean FLSpermessionisAccessible(String salesforceObject, String [] FLSfields){
    String SFobject= salesforceObject;
    String [] FLSfieldsCheck= FLSfields;
    Map<String,Schema.SObjectField> FieldsAccessable ;
    if(SFobject == 'Case'){
        FieldsAccessable = Schema.SObjectType.Case.fields.getMap();
    }else if(SFobject == 'dftly__dftly_user_device__c'){
        FieldsAccessable = Schema.SObjectType.dftly__dftly_user_device__c.fields.getMap();
    }else if(SFobject == 'dftly__ChatDetail__c'){
        FieldsAccessable = Schema.SObjectType.dftly__ChatDetail__c.fields.getMap();
    }
      for (String objectfieldToCheck : FLSfieldsCheck) {
              // Check if the user has create access on the each field
        if (!FieldsAccessable.get(objectfieldToCheck).getDescribe().isAccessible()) {
          System.debug(LoggingLevel.Error, 'you don\'t have access to update Case');
          return false;
        }
      }
      return true;
  }

  public boolean FLSpermessionisCreateable(String salesforceObject, String [] FLSfields){
    String SFobject= salesforceObject;
    String [] FLSfieldsCheck= FLSfields;
    Map<String,Schema.SObjectField> FieldsAccessable ;
    if(SFobject == 'Case'){
        FieldsAccessable = Schema.SObjectType.Case.fields.getMap();
    }else if(SFobject == 'CaseComment'){
        FieldsAccessable = Schema.SObjectType.CaseComment.fields.getMap();
    }
      for (String objectfieldisCreatableCheck : FLSfieldsCheck) {
              // Check if the user has create access on the each field
        if (!FieldsAccessable.get(objectfieldisCreatableCheck).getDescribe().isCreateable()) {
          System.debug(LoggingLevel.Error, 'you don\'t have access to update Case');
          return false;
        }
      }
      return true;
  }

}

The Test method which I tried

@isTest
public class ContactlistController {      
  static testMethod void testContactList (){
    List<Contact> contacts = new List<Contact>();
    for (Integer count = 0; count < 2; count++) {
        contacts.add(new Contact (FirstName = 'John'+count, LastName ='Doe'+count));
    }
    insert contacts;
    String contactId = contacts[0].Id;

    List<Case> cases = new List<Case>();
    for (Integer count = 0; count < 2; count++) {  
        cases.add(new Case (Description = 'Testing'+count, reason ='Testing'+count));
    }
    cases[0].contactid = contactId;
    cases[1].contactid = contactId;
    insert cases;
    String caseId = cases[0].Id;

    CaseComment case_comment =(new CaseComment (commentbody = 'Testing'));
    case_comment.parentid = caseId;
    insert case_comment;
    if(caseId != null){
    List<Case> detailscase=[select casenumber,Description,isclosed, isdeleted,priority,status,subject,type,reason,origin,CreatedDate from case where casenumber= :caseId];
    }
    contact_list_controller cc = new contact_list_controller(new ApexPages.StandardController(contacts[0]));
        cc.getContacts();
        cc.ClosePopup();
        cc.Casecomment_close();
        cc.showPopup();
        cc.casecomment();
        cc.getCases();
        cc.getUserdevice();
        cc.save();
        cc.case_detail();
        cc.chatdetaillist();    
        cc.save_casecomment();
  } 

    @isTest
        static void setAppkey() {     
            dftly__dftly_app__c dac = new dftly__dftly_app__c(Name = 'testing');
            // SET ATTRIBUTES OF dftly_app_contact__c, IE NAME
            insert dac;
             dftly__dftly_app__c dacTest = [SELECT dftly__App_Key__c FROM dftly__dftly_app__c WHERE ID = :dac.Id];
            // USE System.assert() AND System.assertEquals() TO TEST WHETHER THE GUID FIELD IS SET AND WHETHER THE STRING IS IN THE RIGHT FORMAT
        } 

}

The result from the "Force.com Security Scanner", is as below

Query: Test Methods With No Assert This rule identifies Apex Test Methods that do not Assert that the code behaves properly. Verifying that your code works as you expect it to work is the most important part of unit testing. It is important to ensure that all test methods use the System.assert methods to prove that the code behaves as expected. If you do not use any System.assert() method calls, then the tests are not verifying results properly.

References: http://wiki.developerforce.com/index.php/An_Introduction_to_Apex_Code_Test_Methods http://wiki.developerforce.com/index.php/How_to_Write_Good_Unit_Tests Test Methods With No Assert result path 1:

Path Id: -1314612036 Object: testcontactlist in file: classes\ContactlistController.cls L 3: static testMethod void testContactList (){ Test Methods With No Assert result path 2:

Path Id: 209865534 Object: setappkey in file: classes\ContactlistController.cls L 40: static void setAppkey() {

  • It seems that you did write test code. What is the problem with it? What would you like to achieve? – Sebastian Kessel Feb 16 '16 at 7:16
  • @SebastianKessel When I submit the above things to "Force.com Security Scanner". There was an issue stating Query: Test Methods With No Assert, I'll edit my question with the result of "Force.com Security Scanner". – Chandu Feb 16 '16 at 7:23
1

Your Result clearly mentioned that you don't have any assertion check that validate whether your code behaves properly or not. You need to put enough assertion check in your test class.

You can user below methods from System Class:

System.assert(): Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt.

System.assertEquals(): Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt

  • Thank's for the reply. I'll add the above 2 method in the appropriate places. – Chandu Feb 16 '16 at 8:08
  • AxayKumar, This is what the error i'm facing after adding the below code. List<Contact> contact = cc.getContacts(); System.assertEquals(contact,null); System.AssertException: Assertion Failed: Expected: (Contact:{Id=0032800000EZ0wLAAT, Name=John0 Doe0, PhotoUrl=/services/images/photo/0032800000EZ0wLAAT, LastName=Doe0}, Contact:{Id=0032800000EZ0wMAAT, Name=John1 Doe1, PhotoUrl=/services/images/photo/0032800000EZ0wMAAT, LastName=Doe1}), Actual: null – Chandu Feb 16 '16 at 8:21
  • dude, you have to study more about assertion functions in Apex Class, In your case you are comparing "contact"(not null) object with null. You have to make sure that you put proper assertion condition in assert method parameters. – Axaykumar Varu Feb 16 '16 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.