+ Start a Discussion
Falk GaentzschFalk Gaentzsch 

Test Class for a StandardController Extension

Hey Community,

First of all,  I'm pretty new to salesforce.

 

Description of my project :

 

  • I have a single  custom object called 'AccountPlan__c'  it has about 164 fields for dates etc.
  • The object ist linked to a Account by a Master Detail field
  • All fields are shown on a custom page.
  • I also have a apex class with an extension

 

Everything works fine i can save the object, no problems.

But now i want to go the next step: live system.

So i need a test class for my apex class.

I tried really hard to setup a test class but after some day's of trying and a lot of search on Salesforce.com i dont know what to do.

I created new users and Account Plan's but i think I'm running in the wrong direction.

its maybe very simple but like i said, im just a greenhorn and i have to learn everything on my own.

 

here is my apex Class:

 

 

public class newAccountPlan {

  
    public final AccountPlan__c addPlan;   
    public List<Contact> accountContact;   
    public apexpages.standardController controller {get; set;}
  
    public newAccountPlan(ApexPages.StandardController stdController)
    {
      controller = stdController;
        this.addPlan = (AccountPlan__c)Controller.getRecord();
  
    }  
        public List<Contact> getaccountContact()
    {
      string account_id_st = addPlan.Account__c;
         accountContact = [Select id, Name,ReportsTo.Id, Title, ReportsTo.Name, Account.Id from Contact where Account.Id = :account_id_st];
        
        return accountContact;
    } 
            
    public PageReference save()
    {
       try{
            update addplan;
         }
    catch(DmlException ex){
        ApexPages.addMessages(ex);
        }
            return null;
        }   
}
  • the class is searching for a for a reporting structure of my SF account and gives it back for an Org Chart 

I really would appreciate every little comment.

Thanks a lot!!

 

Austin, Texas (I'm a German intern please excuse my grammar ) :smileywink:

 

Best Answer chosen by Admin (Salesforce Developers) 
Falk GaentzschFalk Gaentzsch

Thank you for your reply.

I've solved the problem a couple of minutes ago.

I just needed to connect the Visualforce Page and the test class with the red marked code.

 

static testmethod void validateStandardController(){
            List<Account> accounts = new List<Account>{};
            List<AccountPlan__c> accountPlans= new List<AccountPlan__c>{};
            List<Contact> accountContact = new List<Contact>();
            
            String companyString;

            Account testAccount = new Account(Name='Test Company Name123');
            accounts.add(testAccount);
            insert accounts;
            
            companyString = accounts[0].id;
            AccountPlan__c testAccountPlanInsert = new AccountPlan__c(name = 'Account Plan Test123',Account__c = companyString , accountmanager__c = Userinfo.getUserId());
            accountPlans.add(testAccountPlanInsert);           
        insert accountPlans;
        
         ApexPages.StandardController sc = new ApexPages.StandardController(testAccountPlanInsert);
        newAccountPlan testAccPlan = new newAccountPlan(sc);
        
        PageReference pageRef = Page.AccountPlan;
        pageRef.getParameters().put('id', String.valueOf(testAccountPlanInsert.Id));
        Test.setCurrentPage(pageRef);

    
        
        testAccPlan.getaccountContact();
        testAccPlan.save();
        
        
      }

 

 

 

All Answers

Alok_NagarroAlok_Nagarro

Hi Falk,

 

Can u explain your problem more in depth...

Hav u got error in Test class ? if yes,then  plz  mention what error you had.

And if possible please post your test class.

 

Thanks.

Falk GaentzschFalk Gaentzsch

Thank you for your reply.

I've solved the problem a couple of minutes ago.

I just needed to connect the Visualforce Page and the test class with the red marked code.

 

static testmethod void validateStandardController(){
            List<Account> accounts = new List<Account>{};
            List<AccountPlan__c> accountPlans= new List<AccountPlan__c>{};
            List<Contact> accountContact = new List<Contact>();
            
            String companyString;

            Account testAccount = new Account(Name='Test Company Name123');
            accounts.add(testAccount);
            insert accounts;
            
            companyString = accounts[0].id;
            AccountPlan__c testAccountPlanInsert = new AccountPlan__c(name = 'Account Plan Test123',Account__c = companyString , accountmanager__c = Userinfo.getUserId());
            accountPlans.add(testAccountPlanInsert);           
        insert accountPlans;
        
         ApexPages.StandardController sc = new ApexPages.StandardController(testAccountPlanInsert);
        newAccountPlan testAccPlan = new newAccountPlan(sc);
        
        PageReference pageRef = Page.AccountPlan;
        pageRef.getParameters().put('id', String.valueOf(testAccountPlanInsert.Id));
        Test.setCurrentPage(pageRef);

    
        
        testAccPlan.getaccountContact();
        testAccPlan.save();
        
        
      }

 

 

 

This was selected as the best answer
raghunaadh gunnamraghunaadh gunnam
can anyone help me for writing test class,i'm getting only 45%
public with sharing class SysConct_FeatchObjectController {


    public static SysConct_Provider_detail__c detail;
    public static SysConct_Provider_detail__c d{get;set;}
    public  SysConct_Provider_detail__c detail1{get;set;}
    public List<SelectOption> srcChildObj{get;set;}
    public List<SelectOption> tarChildObj{get;set;}
    public List<SelectOption> trnsaFields{get;set;}
    
        public SysConct_FeatchObjectController(ApexPages.StandardController controller) {
    
    detail1=new SysConct_Provider_detail__c();
        srcChildObj=new List<SelectOption>();
        srcChildObj.add(new SelectOption('--None','--None--'));
        tarChildObj=new List<SelectOption>();
        tarChildObj.add(new SelectOption('--None','--None--'));
        trnsaFields=new List<SelectOption>();
        trnsaFields.add(new SelectOption('--None','--None--'));    

    }

/*
    public SysConct_FeatchObjectController()
    {
        detail1=new SysConct_Provider_detail__c();
        srcChildObj=new List<SelectOption>();
        srcChildObj.add(new SelectOption('--None','--None--'));
        tarChildObj=new List<SelectOption>();
        tarChildObj.add(new SelectOption('--None','--None--'));
    }
    
    */
    
    public  PageReference  ChildObjects()
    {
        String obj=detail1.SysConct_Source_object__c;
        srcChildObj=new List<SelectOption>();
        List<SelectOption> option = new List<SelectOption>();
        System.debug('details11---> '+obj);
        option.add(new SelectOption('--None','--None--'));
        if(obj!=null&&obj!='--None')
        {
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
            Schema.SObjectType leadSchema = schemaMap.get(obj);
            system.debug('----leadSchema------'+leadSchema);
            // system.debug('----leadSchema------'+leadSchema.getSObjectType());
            // Object parObj = leadSchema;
            Schema.DescribeSObjectResult R = leadSchema.getDescribe();
            for (Schema.ChildRelationship cr: R.getChildRelationships()) 
            {
                system.debug('====child object==='+cr.getChildSObject());
                option.add(new SelectOption(String.ValueOf(cr.getChildSObject()),String.ValueOf(cr.getChildSObject())));
            }
            System.debug('----option---'+option);
        }
        srcChildObj.addAll(option);
        system.debug('==========child data===='+srcChildObj);
        return null;
    }   
    public  void TargetChildObjects()
    {
        String obj=detail1.SysConct_Target_object__c;
        tarChildObj=new List<SelectOption>();
        List<SelectOption> option = new List<SelectOption>();
        option.add(new SelectOption('--None','--None--'));
        if(obj!=null&&obj!='--None')
        {
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
            Schema.SObjectType leadSchema = schemaMap.get(obj);
            system.debug('----leadSchema------'+leadSchema);
            // system.debug('----leadSchema------'+leadSchema.getSObjectType());
            // Object parObj = leadSchema;
            Schema.DescribeSObjectResult R = leadSchema.getDescribe();
            for (Schema.ChildRelationship cr: R.getChildRelationships()) 
            {
                system.debug('====child object==='+cr.getChildSObject());
                option.add(new SelectOption(String.ValueOf(cr.getChildSObject()),String.ValueOf(cr.getChildSObject())));
            }
            System.debug('----option---'+option);
        }else{
        
        }
        tarChildObj.addAll(option);
        //return option;
    }   
    public void getTransactionFields(){
        
       String tranObj=detail1.SysConct_Transaction_Object__c;
        trnsaFields = new List<SelectOption>();
        List<SelectOption> options = new List<SelectOption>();
        System.debug('details11---> '+tranObj);
        
        if(tranObj!=null&&tranObj!='--None')
        {
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Schema.SObjectType leadSchema = schemaMap.get(tranObj);
        system.debug('-----leadSchema----->'+leadSchema);
        Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();
        
        Schema.DescribeSObjectResult fieldMaps = leadSchema.getDescribe();
        system.debug('----'+fieldMap);
        system.debug('------------'+fieldMaps);
        
        
        options.add(new SelectOption('--None','--None--'));
        
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            system.debug('====sfield======'+sfield);
            schema.describefieldresult dfield = sfield.getDescribe();
            system.debug('#######' + dfield );
            options.add(new SelectOption(dfield.getname(),dfield.getLabel()));
        }
        }
        trnsaFields.addAll(options);
        system.debug('---trnsaFields------>>>'+trnsaFields);
    }
    public List<SelectOption> getobjNames()
    {
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('--None','--None--'));
        for(Schema.SObjectType f : gd)
        {
            options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
        }
        return options;
    }
    public List<SelectOption> getTrnsctObjNames(){
         List<SysConct_Transaction_Objects__c> tranObj = [select id,name,Value__c from SysConct_Transaction_Objects__c];
         List<SelectOption> options = new List<SelectOption>();
         options.add(new SelectOption('--None','--None--'));
         for(SysConct_Transaction_Objects__c tranRec:tranObj){
             options.add(new SelectOption(tranRec.Value__c,tranRec.name));
         }
    return options;
      
    }
    public pagereference savelist(){
         
        
       String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();////////////
        System.debug('baseUrl =' + baseUrl);///////////
          if( detail1.SysConct_End_point_Url__c == null || detail1.SysConct_End_point_Url__c== ''  ){
            system.debug(' SysConct_End_point_Url__c check. object ...'+detail1);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,'Please enter URL ' ));
            return null;
        }
       
      if( detail1.SysConct_Target_object__c == null || detail1.SysConct_Target_object__c == '--None' ||  detail1.SysConct_Source_object__c== null || detail1.SysConct_Source_object__c == '--None' ){
            system.debug('detail1 check. object ...'+detail1);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,'Please select source and target objects ' ));
            return null;
        }
        
        if( detail1.SysConct_Transaction_Object__c== null || detail1.SysConct_Transaction_Object__c== '--None'  ){
            system.debug(' SysConct_End_point_Url__c check. object ...'+detail1);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING,'Please select Transaction Object ' ));
            return null;
        }
        
        
        try{
         /*   detail = [select SysConct_Merchant_Id__c,SysConct_Provider_Name__c,SysConct_Transaction_Type__c,SysConct_End_point_Url__c,SysConct_Company_Code__c,
                      SysConct_Provider_Type__c,SysConct_Source_object__c,SysConct_Transaction_Object__c,SysConct_Target_Child_Object__c,SysConct_Source_Child_Object__c,SysConct_Target_object__c,SysConct_Transaction_Key__c
                      from SysConct_Provider_detail__c where  SysConct_Provider_Name__c=:detail1.SysConct_Provider_Name__c And SysConct_Transaction_Type__c=:detail1.SysConct_Transaction_Type__c];*/
        }catch(QueryException qe){
            apexpages.addmessages(qe);
            System.debug('The following exception has occurred: ' + qe.getMessage());
        }
        system.debug('detail1....'+detail);
        system.debug('detail1....'+detail1);
        if(detail == null){
            try{
                d = new SysConct_Provider_detail__c();
                system.debug('.....'+detail1);
                d=detail1;
                insert d;
               
                if(d.SysConct_Source_Child_Object__c=='--None')//
                {d.SysConct_Source_Child_Object__c=null;d.SysConct_Target_Child_Object__c=null;}//
                d.SysConct_Reference_Record__c = baseUrl+'/apex/SysConct_PaymentDetailPage?ProviderId='+d.id;//////////////
                update d;
                system.debug('Reference_Record data is============'+d.SysConct_Reference_Record__c);/////////////
                               
            } catch(DmlException e) {
                apexpages.addmessages(e);
                System.debug('The following exception has occurred: ' + e.getMessage());
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert account record. Error: ' + e));
            }
            system.debug('.....'+d);
            PageReference Page = new PageReference('/apex/SysConct_RequestMappingPage?ProviderId='+d.id);
             if(d.SysConct_Transaction_Type__c == detail1.SysConct_Transaction_Type__c  && d.SysConct_Provider_Name__c == detail1.SysConct_Provider_Name__c){
                Page = new PageReference('/apex/SysConct_RequestMappingPage?ProviderId='+detail1.id);
            }
           
            Page.setRedirect(true);
            return Page;
        }
        else{
            try{
                detail1.id=detail.id;
                
                update detail1;
                /////
                system.debug('updated data is:==========='+detail1);
                if(detail1.SysConct_Source_Child_Object__c=='--None')
                {detail1.SysConct_Source_Child_Object__c=null;detail1.SysConct_Target_Child_Object__c=null;}
                
                detail1.SysConct_Reference_Record__c = baseUrl+'/apex/SysConct_PaymentDetailPage?ProviderId='+detail1.id;////////////
                
                update detail1;
                system.debug('updated data is:==========='+detail1);
                system.debug('Reference_Record data is============'+detail1.SysConct_Reference_Record__c);///////////////////
                
            } catch(DmlException e) {
                apexpages.addmessages(e);
                System.debug('The following exception has occurred: ' + e.getMessage());
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Could not insert account record. Error: ' + e));
            }
            system.debug('...'+detail1);
            PageReference Page = new PageReference('/apex/SysConct_RequestMappingPage?ProviderId='+detail1.id+'');
            
            if(detail1.SysConct_Transaction_Type__c == detail.SysConct_Transaction_Type__c  && detail1.SysConct_Provider_Name__c == detail.SysConct_Provider_Name__c){
                Page = new PageReference('/apex/SysConct_RequestMappingPage?ProviderId='+detail1.id);
            }
            
            Page.setRedirect(true);
            return Page;
        }
      }
}



@isTest
public class SysConct_FeatchObjectControllerTest {
    public static SysConct_Provider_detail__c pd;
    public static SysConct_Provider_detail__c detail;
    private static testmethod void testUtils(){
        
        SysConct_Transaction_Objects__c st = new SysConct_Transaction_Objects__c();
        st.name='PaymentTransaction';
        st.value__c='SysConct_Audit_mapping__c';
        SysConct_Provider_detail__c s= new SysConct_Provider_detail__c();
        s.SysConct_Merchant_Id__c = 'FOR1234';
        s.SysConct_Provider_Name__c = 'Cybersource';
        // s.SysConct_Target_Child_Object__c = 'OrderItem';
        // s.SysConct_Source_Child_Object__c = 'OrderItem';
        s.SysConct_Transaction_Object__c = st.value__c;
        s.SysConct_End_point_Url__c = 'https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor';
        s.SysConct_Provider_Type__c = 'Payment';
        s.SysConct_Source_object__c = 'Order';
        s.SysConct_Target_object__c = 'Order';
        s.SysConct_Tansaction_Related_List__c='order__c';
        s.SysConct_Transaction_Key__c = '8H1ud/HaCE5L5JFhqowJVjyrwig0UPGXtOlcMvBeeiBbLdFqX1gIf8RtCF9WMvw6QozkW4oK6Yo6Ysganj+BziukFh34K5TNNRm71NiOTyYTH8r0k4E1JQ9jwDQBgSukDrFh5mMb5OGQXWMjX5Fg5TgCZuYf2YXkNdnBWPaY4TlJuZfSqb3M+pVNjLxfk3QrPrGy4sv44bnBAeFBNNGGj1IPUFAXVb5DU4vO/PX0S+VNL8PbcRTx9BNX5r5oqgcl3WpiTiAaDv/noX3FnJUbDfRV+dyoAwJ33ghm35KfrXy29I8/DrpcFvHfwfXAHaO+CypwFfpZ9r+2QpQ4vxYGHA==';
        s.SysConct_Transaction_Type__c = 'Authorization';
        insert s;
        detail = s;
        update detail;
        system.debug('----s-----'+s);
       // s.SysConct_Merchant_Id__c='Forsys';
       
        
        pd=[select id,SysConct_Target_Child_Object__c,SysConct_Source_object__c,SysConct_Target_object__c,SysConct_Transaction_Object__c,SysConct_Source_Child_Object__c,
            SysConct_Provider_Name__c,SysConct_Provider_Type__c,SysConct_Password__c,SysConct_Merchant_Id__c,SysConct_End_point_Url__c,SysConct_Customer_Transaction_Id__c,
            SysConct_Company_Code__c,SysConct_Account_Number__c from SysConct_Provider_detail__c where id=:s.id];
        
        
                test.startTest();

         ApexPages.StandardController sc = new ApexPages.StandardController(detail);
                SysConct_FeatchObjectController controller = new SysConct_FeatchObjectController(sc);
SysConct_Transaction_Objects__c st1 = new SysConct_Transaction_Objects__c();
        st1.name='PaymentTransaction';
        st1.value__c='SysConct_Audit_mapping__c';
        insert st1;
        s=[select id,SysConct_Target_Child_Object__c,SysConct_Source_object__c,SysConct_Target_object__c,SysConct_Transaction_Object__c,SysConct_Source_Child_Object__c,
            SysConct_Provider_Name__c,SysConct_Provider_Type__c,SysConct_Password__c,SysConct_Merchant_Id__c,SysConct_End_point_Url__c,SysConct_Customer_Transaction_Id__c,
            SysConct_Company_Code__c,SysConct_Account_Number__c from SysConct_Provider_detail__c where id=:s.id];
         s.SysConct_Merchant_Id__c = 'FOR1234';
        s.SysConct_Provider_Name__c = 'Cybersource';
        // s.SysConct_Target_Child_Object__c = 'OrderItem';
        // s.SysConct_Source_Child_Object__c = 'OrderItem';
        s.SysConct_Transaction_Object__c = st1.value__c;
        s.SysConct_End_point_Url__c = 'https://ics2wstesta.ic3.com/commerce/1.x/transactionProcessor';
        s.SysConct_Provider_Type__c = 'Payment';
        s.SysConct_Source_object__c = 'Order';
        
        s.SysConct_Tansaction_Related_List__c='order__c';
        s.SysConct_Transaction_Key__c = '8H1ud/HaCE5L5JFhqowJVjyrwig0UPGXtOlcMvBeeiBbLdFqX1gIf8RtCF9WMvw6QozkW4oK6Yo6Ysganj+BziukFh34K5TNNRm71NiOTyYTH8r0k4E1JQ9jwDQBgSukDrFh5mMb5OGQXWMjX5Fg5TgCZuYf2YXkNdnBWPaY4TlJuZfSqb3M+pVNjLxfk3QrPrGy4sv44bnBAeFBNNGGj1IPUFAXVb5DU4vO/PX0S+VNL8PbcRTx9BNX5r5oqgcl3WpiTiAaDv/noX3FnJUbDfRV+dyoAwJ33ghm35KfrXy29I8/DrpcFvHfwfXAHaO+CypwFfpZ9r+2QpQ4vxYGHA==';
        s.SysConct_Transaction_Type__c = 'Authorization';
       
        PageReference pageRef = Page.SysConct_ProviderDetails;
        Test.setCurrentPage(pageRef);
        system.debug('---pd------>>'+pd);
        // SysConct_Provider_detail__c detail1 = pd;
        controller.ChildObjects();
        s.SysConct_Target_object__c = 'Order';
        controller.TargetChildObjects();
        controller.getTransactionFields();
        controller.getobjNames();
        controller.getTrnsctObjNames();
        controller.savelist();
        test.stopTest();
    }
 
}