0

From past few days i'm working on writing an Apex test for my controller extension. I've created a dummy record for my custom object then passing the id in the constructor while invoking my extension.

I'm passing the id with getParameters().put('id',myobject.id) before creating the instance of the extension.

But the problem is my test is failing and after brainstorming for hours i got to to it's missing a fieldset. I'm not sure how to pass the fieldset or even if it is actually required.

Ideally i'd be able to pass the necessary data to my vf page and hit save. So fieldset is required or not, i'm not much sure. I'm however searching for a way to how to pass data into my vf page.

Another problem is code coverage. Many of the methods in the controller are private. I can't make them public, else i'll scare off the people who wrote the controller.

I believe the private methods are called in the constructor but then how would i pass data into those methods i'm not sure.

The controller is a giant so i'm not posting the codes here.

Any advice on this would be definitely needed.

    /*
       * Name      : SBSCustomerSupportRLItemGridController
       * Description  : SBS Customer Support Request Line Items VF Table & Spreadsheet View 
       * Maintenance History:
       * 03/10/2015 - 1.0 - Created    
*/
global with sharing class SBSCustomerSupportRLItemGridController {


    public SBS_Customer_Support__c SBSRequest                { get; set; }           // Query SBS_Customer_Support__c to get requestType of current record.

    public String recordType{ get; set; }           // Variable stores record type of current record.
    public String opCoPlant{ get; set; }           // Variable stores record type of current record.
    public String fieldsetAPI{ get; set; }
    public String mode{ get; set; }           // variable use to identify if line item is created/edited.
    public String scId{ get; set; }           // Variable stores id of current SBS Costing Request record.
    public Integer currentRow{ get; set; }           // for cloning
    public Integer numRowsToAdd{ get; set; }           // No of rows to add on click of add 5 Rows button
    public Integer indexToRemove{ get; set; }           // stores index of line item record from where record is to be deleted.
    public Integer numRowsToRemove{ get; set; }           // Specifies how many records are to be deleted from index.

    public Map<String,String> mapColumnHeadersToFieldApi{ get; set; }           // Map to store column headers label and its field api.
    public Map<String,Boolean> isFieldPicklist{ get; set; }           // Map to specify which field is of picklist type.
    public List<SBSCustomerSRLineItem> lineItems{ get; set; }           // List of wrapper class to bind Costing line item on page and index.
    public transient List<String> lstColumnHeaders{ get; set; }           // List of headers to be displayed in table as well as Spreadsheet.
    public String selectedIndexToDel{ get; set; }           // List of row indexes to delete.
    //public String strMaterialCodeLabel                                { get;set;  }           //String storing static value 'Material Code'.
    //public String strMaterialNameLabel                                { get;set;  }           //String storing static value 'Material Name'.
    public SBS_Customer_Support_Line_Item__c obj;
    String strQuery; 

    //Constructor
    public SBSCustomerSupportRLItemGridController( ApexPages.StandardController controller) {

        lineItems = new List<SBSCustomerSRLineItem>();
        lstColumnHeaders = new List<String>();
        isFieldPicklist = new Map<String,Boolean>();
        mapColumnHeadersToFieldApi = new Map<String,String>();

        Map<String, Schema.FieldSet> fieldSetToValues = Schema.SObjectType.SBS_Customer_Support_Line_Item__c.fieldSets.getMap();
        List<Schema.FieldSetMember> lstFields = new List<Schema.FieldSetMember>();

        selectedIndexToDel = '';
        //strMaterialCodeLabel = 'Material Code';
        //strMaterialNameLabel = 'Material Name';

        scId = ApexPages.currentPage().getParameters().get( 'scId' );
        mode = ApexPages.currentPage().getParameters().get( 'mode' );

        /* get SBS Customer Support request data*/
        SBSRequest = [ SELECT  Id, Request_Type__c, RecordType.DeveloperName, RecordType.Name, RecordTypeId, OpCo_Plant__c
                       FROM SBS_Customer_Support__c 
                       WHERE Id = :scId
        ];

        recordType = SBSRequest.RecordType.Name; 
        opCoPlant = SBSRequest.OpCo_Plant__c; 

        ApexPages.Message myMsg = new ApexPages.Message( ApexPages.severity.info, 'NOTE: Be sure to click "Save" prior to leaving this page or your updates will be lost!' );
        ApexPages.AddMessage( myMsg );

        String strField = '';
        strQuery = 'Select SBS_Customer_Support__c,';


        if(!fieldSetToValues.isEmpty()) {
            for(String key : fieldSetToValues.KeySet()) {

                 if(recordType == fieldSetToValues.get(key).getLabel()) {
                    fieldsetAPI = fieldSetToValues.get(key).getName();
                    lstFields = readFieldSet(fieldSetToValues.get(key).getName(),'SBS_Customer_Support_Line_Item__c');
                 }
            }
        }
        if(!lstFields.isEmpty()) {
            for(Schema.FieldSetMember objFields : lstFields) {
                    mapColumnHeadersToFieldApi.put(objFields.getLabel(),objFields.getFieldPath());
                    lstColumnHeaders.add(objFields.getLabel());
                    strField += objFields.getFieldPath() + ', ';
            }
        }

        system.debug('@@mapColumnHeadersToFieldApi-'+mapColumnHeadersToFieldApi);
        system.debug('@@lstColumnHeaders-'+lstColumnHeaders);

        strField = strField.subString(0,strField.length()-2);
        system.debug('@@strField-'+strField);

        strQuery +=  strField + ' FROM SBS_Customer_Support_Line_Item__c WHERE SBS_Customer_Support__c = : scId';

        Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe(); 
        Schema.SObjectType  objectType = globalDescribe.get('SBS_Customer_Support_Line_Item__c');
        Map<String, Schema.SObjectField> objectFieldMap  = objectType.getDescribe().fields.getMap();

        for(String strFields : lstColumnHeaders) {

            String strColFieldName = mapColumnHeadersToFieldApi.get(strFields);
            if(String.valueOf(objectFieldMap.get(strColFieldName).getDescribe().getType()) == 'PICKLIST') {
                isFieldPicklist.put(strFields,true);
            }
            else {
                isFieldPicklist.put(strFields,false);
            }

        }

       /* determine if user is editing or adding new records   
       * if adding, we first add the blank new records to the db, from that point, the functionality is the same as editing. */   
        if ( mode == 'edit' ) {
            instantiateList();
        } 
        else if( mode == 'add' ){
            addNewRecords(20);
        } 
    }

    //Retrieve fields from fieldset
    private static List<Schema.FieldSetMember> readFieldSet(String fieldSetName, String ObjectName) {

        Schema.DescribeSObjectResult DescribeSObjectResultObj = Schema.getGlobalDescribe().get(ObjectName).getDescribe();
        Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);
        return fieldSetObj.getFields(); 

    }  

    //Instantiate line item to be added on load.
     private void instantiateList() {

        if(strQuery != null && strQuery != '')
        {
            List<SBS_Customer_Support_Line_Item__c> scli = database.query(strQuery);
            lineItems.clear();

            for ( Integer i = 0; i < scli.size();i++ ) {
                lineItems.add( new SBSCustomerSRLineItem( scli[i], i+1) );
            }

        }
    }   

    //Method executed on click on Save button
    public PageReference save() {

        system.debug('==========LineItems=========='+lineItems);
        Boolean isProductNameInvalid = false;
        deleteUnusedRecords(selectedIndexToDel);
        System.debug( 'Inside Save' );
        String errorMsg = '';
        Boolean errorFound = false;
        ApexPages.Message myMsg;
        PageReference pr; 

        map<String, list<syscoProductItemDetails>> mapMaterialCodeTosyscoProductItemDetails = new map<String, list<syscoProductItemDetails>>();

        if ( lineItems.size() == 0 ) 
        {
            addNewRecords(20);
            myMsg = new ApexPages.Message( ApexPages.severity.warning, 'There were no records to save.' );
            ApexPages.AddMessage( myMsg );  
            return null;        

        }

        // get all Material_Code__c to query the SyscoProductNames
        for ( SBSCustomerSRLineItem scli : lineItems )  {

            List<syscoProductItemDetails> lstWrapper = new List<syscoProductItemDetails>();
            lstWrapper.add(new syscoProductItemDetails('INVALID MATERIAL CODE' ,''));

            mapMaterialCodeTosyscoProductItemDetails.put(scli.item.Material_Code__c, lstWrapper );
        }


        try{

            for(Sysco_Product_Item__c objProductItem :  [SELECT OpCo__c, OpCo__r.OpCo_ID__c, Name, Id, SUPC__c 
                                                        FROM Sysco_Product_Item__c 
                                                        WHERE SUPC__c IN :mapMaterialCodeTosyscoProductItemDetails.keySet() AND OpCo__r.OpCo_ID__c =: opCoPlant]){ //strcurrentUserOpco

                List<syscoProductItemDetails> lstWrapper = new List<syscoProductItemDetails>();
                lstWrapper.add(new syscoProductItemDetails(objProductItem.Name ,objProductItem.Id));

                mapMaterialCodeTosyscoProductItemDetails.put(objProductItem.SUPC__c, lstWrapper );
            }
        }
        catch(Exception ex){

            system.debug('## Exception is:: ' + ex);
        }

        List<SBS_Customer_Support_Line_Item__c> srUpdates = new List<SBS_Customer_Support_Line_Item__c>();
        for ( SBSCustomerSRLineItem scli : lineItems )  {

            Boolean isRecordAlreadyExist = false;
            list<syscoProductItemDetails> lstProdDet = new list<syscoProductItemDetails>();
            for(String strColApi : mapColumnHeadersToFieldApi.values()) {
                if(isRecordAlreadyExist == false) {

                    if(scli.item.Material_Code__c != '' && scli.item.Material_Code__c != null && mapMaterialCodeTosyscoProductItemDetails.containskey(scli.item.Material_Code__c)) {

                        lstProdDet = mapMaterialCodeTosyscoProductItemDetails.get(scli.item.Material_Code__c); //SBSCustomerSupportRLItemGridController.getMaterialName(scli.item.Material_Code__c);
                        scli.item.Description__c = lstProdDet[0].strSyscoProductName;
                        if(lstProdDet[0].strSyscoProductName == 'INVALID MATERIAL CODE'){
                            isProductNameInvalid = true;
                        }
                    }
                    else{
                        scli.item.Description__c = null;
                    }

                    if(scli.item.Description__c != 'INVALID MATERIAL CODE' && scli.item.Description__c != '' && scli.item.Description__c != null){
                        scli.item.Material__c = Id.valueOf(lstProdDet[0].strSyscoProductId);
                    }
                    else{
                        scli.item.Material__c = null;
                    }

                    if(scli.item.get(strColApi) != null && scli.item.get(strColApi) != ''){
                        isRecordAlreadyExist = true;
                        srUpdates.add(scli.item);
                        continue;
                    }
                }
            }
        }

        if(isProductNameInvalid){
            myMsg = new ApexPages.Message( ApexPages.severity.warning, 'INVALID MATERIAL CODE' );
            ApexPages.AddMessage( myMsg ); 
            return null; 
        }

        if(srUpdates.isEmpty()){
            myMsg = new ApexPages.Message( ApexPages.severity.warning, 'There were no records to save.' );
            ApexPages.AddMessage( myMsg );  
            return null;   
        }

        try{
            if(!srUpdates.isEmpty())
                upsert(srUpdates);
        }
        catch(Exception ex){
            String strErrormsg = '';
            if(ex.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
                strErrormsg = ex.getMessage().substring(ex.getMessage().indexOf('FIELD_CUSTOM_VALIDATION_EXCEPTION')+35,ex.getMessage().lastIndexOf(':'));
            }
            else{
                strErrormsg = ex.getMessage();
            }
            ApexPages.addMessage( new ApexPages.Message( ApexPages.Severity.ERROR,strErrormsg) );
            errorFound = true;
        }

        if ( ! errorFound ) {
            myMsg = new ApexPages.Message( ApexPages.severity.confirm, 'Line Items were successfully updated.' );
            ApexPages.AddMessage( myMsg );

            /* place ids in new rows */
            for ( Integer i = 0; i < srUpdates.size(); i++ ){
                if ( lineItems[i].item.Id == null ) {
                    lineItems[i].item.Id = srUpdates[i].Id;
                }
            }
        }

        return null;    
    }
    //Method executed on click of add 5 Records button.
    public PageReference add5NewRecords() {
        addNewRecords( 5 );
        return null;
    }

    public void addNewRecords() {
        system.debug('============numRowsToAdd ==========='+this.numRowsToAdd);
        addNewRecords( this.numRowsToAdd );
    }

    private void addNewRecords( Integer qty ) {
        system.debug('============qty ==========='+qty);
        if ( qty == null || qty == null ){
             return;
        }
        Integer start = lineItems.size();
        system.debug('============start ==========='+start);
        for ( Integer i = start; i < start+qty; i++ ) {
            system.debug('======test======scId ==========='+scId);
            SBS_Customer_Support_Line_Item__c scli = new SBS_Customer_Support_Line_Item__c( SBS_Customer_Support__c = scId);
            lineItems.add( new SBSCustomerSRLineItem( scli, i+1) );
        }
    }

    //Method executed on click of DeleteAll button.
     public Pagereference deleteAllRecords() {
        /* delete all records saved in db */
        PageReference pgref = null;
        List<Id> scliToDelete = new List<Id>();
        for ( SBSCustomerSRLineItem scli : lineItems ) {
            if ( scli.item.Id != null )
                scliToDelete.add( scli.item.Id );
        }
        if ( scliToDelete.size() >0 )
            Database.deleteResult[] dr = Database.delete( scliToDelete );

        String strMode = ApexPages.currentPage().getParameters().get( 'mode' );
        String scId = ApexPages.currentPage().getParameters().get( 'scId' );
        pgref = new Pagereference('/apex/SBSCustomerSupportRLItemGrid?mode='+strMode+'&scId='+scId);
        pgref.setredirect(true);
        return pgref;
         //instantiateList();
        //addNewRecords( 20 );
    }   

    //Method executed on click of Return to Costing Request button.
    public PageReference back() {
        PageReference pr = new PageReference( '/' + scId );
        pr.setRedirect( true );
        return pr;
    }

    public void removeRecords() {
        removeRecords( this.indexToRemove, this.numRowsToRemove );
    }

    private void removeRecords( Integer indexToRemove, Integer numRowsToRemove ) {
        if ( indexToRemove >= lineItems.size() ) return;
        if ( indexToRemove + numRowsToRemove >= lineItems.size() )
            numRowsToRemove = lineItems.size() - indexToRemove;
        for ( Integer i = indexToRemove; i < indexToRemove+numRowsToRemove; i++ ){
            lineItems.remove(indexToRemove);
        }
        renumberList();
    }
    //Method exceuted on click of Clone Icon
     public PageReference cloneRecord(){

        /* clone Support Request */
        SBS_Customer_Support_Line_Item__c srli = lineItems[currentRow -1].item.clone();

        /* add to wrapper class and insert into list*/
        SBSCustomerSRLineItem srlItem = new SBSCustomerSRLineItem( srli, lineItems.size()+1);

        if ( currentRow == lineItems.size() ){
            lineItems.add( srlItem );       // cloning last row in table.
        } else {
            lineItems.add( currentRow, srlItem );   //cloning other row.
            renumberList();
        }

        return null;
    }
    private void renumberList(){
        /* renumber list */
        for ( Integer i = 0; i < lineItems.size(); i++ ) {
            lineItems[i].idx = i+1;
        }
    }

    public void deleteUnusedRecords(String indexTodel) {

        List<Id> scliToDelete = new List<Id>();
        List<SBSCustomerSRLineItem> lstLineItemsToUpdate = new List<SBSCustomerSRLineItem>();
        set<Id> setScliToDelete = new set<Id>();
        set<Integer> scliIndexToDel = new set<Integer>();

        if(indexTodel != '')
        {
             for(String strIndex : indexTodel.split(',')) 
             {
                if(strIndex != '' && strIndex != 'undefined')
                {
                    scliIndexToDel.add(Integer.valueOf(strIndex));
                }
            }

        }

        for ( Integer i = 0; i < lineItems.size(); i++ ) {

            if(scliIndexToDel.contains(lineItems[i].idx))
            {
                 if ( lineItems[i].item.Id != null )    
                    setScliToDelete.add( lineItems[i].item.Id );
            }
            else 
            {
                lstLineItemsToUpdate.add(lineItems[i]);
            }


        }
        lineItems.clear();
        lineItems.addAll(lstLineItemsToUpdate);
        scliToDelete.addAll(setScliToDelete);
        renumberList();

        if ( ! scliToDelete.isEmpty() ){
            Database.DeleteResult[] dr = Database.delete( scliToDelete );
        }
        return;
    }

     @RemoteAction
    public static List<syscoProductItemDetails> getMaterialName( String opCoPlantId, String materialCode ){


        List<syscoProductItemDetails> lstWrapper = new List<syscoProductItemDetails>();
        //List<User> currentUserOpco = new List<User>();
        String strname = 'N/A';
        String strId = '';
        //currentUserOpco = [Select OpCo_ID__c, Id From User where Id =: userinfo.getUserId() LIMIT 1];
        //String strcurrentUserOpco = currentUserOpco[0].OpCo_ID__c;

        String query = 'SELECT OpCo__c, OpCo__r.OpCo_ID__c, Name FROM Sysco_Product_Item__c WHERE SUPC__c = :materialCode AND OpCo__r.OpCo_ID__c =: opCoPlantId LIMIT 1'; // strcurrentUserOpco

        if ( query != '' ) {
            sObject[] products = Database.query( query );
            strname = ( ! products.isEmpty() )? (String) products[0].get( 'Name' ) : 'INVALID MATERIAL CODE';
            strId = ( ! products.isEmpty() )? (String) products[0].get( 'Id' ) : '';
        }
        lstWrapper.add(new syscoProductItemDetails(strname,strId));
        return lstWrapper;   
    }

    //Wrapper class
    public class SBSCustomerSRLineItem {
        public Integer idx                      { get; set; }
        public SBS_Customer_Support_Line_Item__c item    { get; set; }
        public String displayMode               { get; set; }
        public Boolean remove                   { get; set; }
        public String strMaterialName           { get; set; }


        public SBSCustomerSRLineItem( SBS_Customer_Support_Line_Item__c item, Integer index ){
            this.item = item;
            this.idx = index;
        }
     }
     //Wrapper class to bind Column header and its data type.
     public class ColHeaderToFieldTypeWrapper {

        public String strColLabel                   {  get; set; }
        public Boolean isPicklistFieldType          {  get; set; }
        public String strColType                    {  get; set; }


        public ColHeaderToFieldTypeWrapper(string strColLabel,Boolean isPicklistFieldType,String strColType){

            this.strColLabel = strColLabel;
            this.isPicklistFieldType = isPicklistFieldType;
            this.strColType = strColType;
        }

    }

    public class syscoProductItemDetails {

            public String strSyscoProductName;
            public String strSyscoProductId;

            public syscoProductItemDetails(String strSyscoProductName,String strSyscoProductId) {

                this.strSyscoProductName = strSyscoProductName;
                this.strSyscoProductId = strSyscoProductId;
            }
    }

    //Method used to get data type of field value displayed in each colum.
    @RemoteAction
    public static List<ColHeaderToFieldTypeWrapper> getColumnHeaderType(String reqType) {

        List<String> lstColumnHeaders = new List<String> ();
        List<ColHeaderToFieldTypeWrapper> lstWrapper = new List<ColHeaderToFieldTypeWrapper>();
        List<Schema.FieldSetMember> lstFields = new List<Schema.FieldSetMember>();

        Map<String, Schema.FieldSet> fieldSetToValues = Schema.SObjectType.SBS_Customer_Support_Line_Item__c.fieldSets.getMap();
        Map<String,String> mapColumnHeadersToFieldApi = new Map<String,String>();
        Schema.DescribeSObjectResult DescribeSObjectResultObj = Schema.getGlobalDescribe().get('SBS_Customer_Support_Line_Item__c').getDescribe();

        if(!fieldSetToValues.isEmpty()) {
            for(String key : fieldSetToValues.KeySet()) {
                 if(reqType == fieldSetToValues.get(key).getLabel()) {

                     Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetToValues.get(key).getName());
                     lstFields =  fieldSetObj.getFields();
                 }
            }
        }

        if(!lstFields.isEmpty()) {
            for(Schema.FieldSetMember objFields : lstFields) {
                mapColumnHeadersToFieldApi.put(objFields.getLabel(),objFields.getFieldPath());
                lstColumnHeaders.add(objFields.getLabel());
            }
        }

        Map<String, Schema.SObjectType> globalDescribe = Schema.getGlobalDescribe(); 
        Schema.SObjectType  objectType = globalDescribe.get('SBS_Customer_Support_Line_Item__c');
        Map<String, Schema.SObjectField> objectFieldMap  = objectType.getDescribe().fields.getMap();
        ColHeaderToFieldTypeWrapper objWrapper;

        for(Integer index = 0;index< lstColumnHeaders.size();index++) {

            String strColFieldName = mapColumnHeadersToFieldApi.get(lstColumnHeaders[index]);
            String strFieldType = String.valueof(objectFieldMap.get(strColFieldName).getDescribe().getType());

            if(String.valueOf(objectFieldMap.get(strColFieldName).getDescribe().getType()) == 'PICKLIST') {
               lstWrapper.add(new ColHeaderToFieldTypeWrapper(lstColumnHeaders[index],true,strFieldType));
            }
            else {
                 lstWrapper.add(new ColHeaderToFieldTypeWrapper(lstColumnHeaders[index],false,strFieldType));
            }

        }
        return lstWrapper;      
    }
}

Thanks, Sangram

  • First of all please share your code. Your second concern about how to call private methods you could put the annotation @testVisible and you can test your method without having to make it public. If you publish more code or at least the bit that you have wrote than we can help you more. – Mihai Neagoe Mar 14 '15 at 9:46
  • I wish i could post my test class as well. After handling the exceptions, finally my test class is passing. I feel it's good to manually check values using system.assert and handle all other exceptions, which might lead to a failing test. I can see the code coverage my mavensmate 34%. – user477 Mar 14 '15 at 12:53
  • Is it possible to see the code coverage in developer console as well. I see it's flagged as [code covergae : none]. Does developer console requires additional settings to see the lines covered. – user477 Mar 14 '15 at 12:55

Your Answer

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