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
Salesforce Developer 60Salesforce Developer 60 

Test Class for Account and ContactRole Extension

This is my controller. Can anyone suggests me how to add test class for this controller. And one more question in this line AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id); am hardcode the contactId. So how to remove this from here.
public class AccountAndcontactrolesEditExtensionV2{
    private ApexPages.StandardController std;
     
    // the associated AccountContactRoles
   public List<AccountContactRole> AccountContactRoles;
      
    // the chosen AccountContactRole id - used when deleting a AccountContactRole
    public Id chosenAccountContactRoleId {get; set;}
     
    public AccountAndcontactrolesEditExtensionV2(ApexPages.StandardController stdCtrl)
    {
     std=stdCtrl;
    }
     
    public Account getAccount()
    {
     return (Account) std.getRecord();
    }
 
    private boolean updateAccountContactRoles()
    {
        boolean result=true;
        if (null!=AccountContactRoles)
           {
           List<AccountContactRole> updConts=new List<AccountContactRole>();
              try
              {
               update AccountContactRoles;
              }
              catch (Exception e)
              {
                 String msg=e.getMessage();
                 integer pos;
                  
                 // if its field validation, this will be added to the messages by default
                 if (-1==(pos=msg.indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION, ')))
                 {
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, msg));
                 }
                  
                 result=false;
              }
           }
            
           return result;
    }
     
    public PageReference saveAndExit()
    {
     boolean result=true;
    result=updateAccountContactRoles();
      
     if (result)
     {
        // call standard controller save
        return std.save();
     }
     else
     {
      return null;
     }
    }
     
    public PageReference save()
    {
     Boolean result=true;
     PageReference pr=Page.contactRole2;
     if (null!=getAccount().id)
     {
      result=updateAccountContactRoles();
     }
     else
     {
      pr.setRedirect(true);
     }
      
     if (result)
     {
        // call standard controller save, but don't capture the return value which will redirect to view page
        std.save();
           ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Changes saved'));
     }
        pr.getParameters().put('id', getAccount().id);
      
     return pr;
    }
 
    public void newAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          AccountContactRole cont=new AccountContactRole(Role='None',ContactId='0032800000CIMN0', IsPrimary=false, AccountId=getAccount().id);
          insert cont;
         
          // null the AccountContactRoles list so that it is rebuilt
          AccountContactRoles=null;
       }
    }
     
    public void deleteAccountContactRole()
    {
       if (updateAccountContactRoles())
       {
          if (null!=chosenAccountContactRoleId)
          {
             AccountContactRole cont=new AccountContactRole(Id=chosenAccountContactRoleId);
              delete cont;
        
           // null the AccountContactRoles list so that it is rebuilt
              AccountContactRoles=null;
              chosenAccountContactRoleId=null;
          }
       }
    }
     
   public List<AccountContactRole> getAccountContactRoles()
    {
       if ( (null!=getAccount().id) && (AccountContactRoles == null) )
       {
           AccountContactRoles=[SELECT Id,Role,AccountId,IsPrimary,ContactId
                         FROM AccountContactRole 
                         WHERE AccountId = : getAccount().ID
                         ORDER BY CreatedDate];
       }
                           
       return AccountContactRoles;
    }
}

 
pconpcon
There are lots of ways to remove that hardcoded contactId.  It will all depend on how you are determining which contact gets assigned there.  Just seeing this class does not provide much context as to what you are actually doing.  Since this is a class for an Account then you will need to figure out what contact(s) you want to use and then query them from the account record.

As for testing this, there is a lot to cover here.  I would recommend that you read over this article [1] to plan your tests and read over this article [2] to familiarize yourself with testing controller extensions.  If after reading those you have any specific questions, please feel free to ask them.

[1] http://blog.deadlypenguin.com/blog/testing/strategies/
[2] https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm
Salesforce Developer 60Salesforce Developer 60
Thanks @Pcon for your response. I followed your suggestions and add my test class but it covers 71% code coverage. How to increase more code coverage here. Take a look below my code.
@IsTest(SeeAllData=true)
private class TestAccountAndcontactroles {
    
  static testMethod void validateHelloWorld() {

        
 Account testAccount = new Account();
 testAccount.Name='Test Account' ;
 insert testAccount;
 
 Contact con = new Contact();
 con.LastName='test';
 con.AccountId= testAccount.Id;
 con.Email='ds@gmail.com';
 insert con;
      

 AccountContactRole cont=new AccountContactRole();
     cont.role ='Businesss uesr';
     cont.ContactId=con.Id;
     cont.IsPrimary=false;
     cont.AccountId = testAccount.Id;
     insert cont;
     
     
     List<AccountContactRole> updCont = new List<AccountContactRole>();
     updCont.add(cont);
     update updCont; 
     
              
 Test.StartTest(); 
  ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
  AccountAndcontactrolesEditExtensionV2 testAccPlan = new AccountAndcontactrolesEditExtensionV2(sc);

  PageReference pageRef = Page.ContactRole2; // Add your VF page Name here
  pageRef.getParameters().put('id', String.valueOf(testAccount.Id));
  Test.setCurrentPage(pageRef);
  testAccPlan.getAccount();
  testAccPlan.updateAccountContactRoles();
  testAccPlan.saveAndExit();
  testAccPlan.save();
 
 
 testAccPlan.newAccountContactRole();
 testAccPlan.deleteAccountContactRole();
 testAccPlan.getAccountContactRoles();
  
  //testAccPlan.save(); call all your function here
 Test.StopTest();
    }
    
}

User-added image