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
Sarthak Bajaj 14Sarthak Bajaj 14 

Issue related to test class coverage

Apex class
public with sharing class SF1AddProductCC {
    
    public String recordType { get; set;} 
    public boolean priceBookSelected { get; set; }
    public boolean GVWSOpp { get; set; }
    public boolean nonGVWSOpp { get; set; }

    public Opportunity opp {get; set;}
    public list<PriceBookWrapper> lstPriceBooks { get; set; }
    public list<OppLineItemWrapper> lstOppItems { get; set; }
    
    public boolean productSearched { get; set; }
    public List<SelectOption> lstPriceBookOptions{ get; set; }
    public String priceBookId { get; set; }
    
    
    public string keyword { get; set; }
    public List<SelectOption> lstFilterFields{ get; set; }
    public string field { get; set; }
    private ApexPages.StandardController standardController; 
    
    
    
    public SF1AddProductCC(ApexPages.StandardController standardController){
        
        
        this.standardController = standardController;
        opp = (Opportunity) standardController.getRecord();
        
        recordType = ApexPages.currentPage().getParameters().get('recordType');
        
        priceBookSelected = false;
        productSearched = false;
               
String recordtypename = [select recordtype.name from opportunity where id =: opp.id limit 1].recordtype.name;
        system.debug('recordtypename#####'+ recordtypename);

if(recordtypename == 'GVWS Zone Opportunity' || recordtypename == 'GVWS National Accounts Opportunity')
{
GVWSOpp = true;
nonGVWSOpp = false;
   }
else
{
GVWSOpp = false;
nonGVWSOpp = true;
}

        if(GVWSOpp == false && nonGVWSOpp == true)
        {    
         //TODO: Check if the PriceBook is already selected
        system.debug('****before getPriceBookOptions method*****');
        getPriceBookOptions();
        system.debug('****after getPriceBookOptions method*****');
        }
        setProductSearchLists();
          

        
        /*
            If there is only one Pricebook2 entry, we set the selected
            Pricebook2 and then call save.
        */
        
         if(GVWSOpp == false && nonGVWSOpp == true)
            {
        if(lstPriceBookOptions.size() == 1){
          
            priceBookId = lstPriceBookOptions[0].getValue();
            system.debug('********priceBookId for Other*********'+priceBookId );
            }
            }      
            else if (GVWSOpp == true && nonGVWSOpp == false)
            {
             if(recordtypename == 'GVWS Zone Opportunity')
             {
             priceBookId = [SELECT Id FROM Pricebook2 WHERE Name = 'GVWS Zone Price Book'].Id;
             system.debug('********priceBookId for Zone*********'+priceBookId );
             }
             else if (recordtypename == 'GVWS National Accounts Opportunity')
             {
             pricebookid =  [SELECT Id FROM Pricebook2 WHERE Name = 'GVWS NA Price Book'].Id  ;                                 
             system.debug('********priceBookId for NA*********'+priceBookId );
             }    
                  system.debug('Pricebook Id is'+pricebookId);
      
            }
            save();
        }
        
       //  end of constructor
    
    
    public void save(){
        list<PriceBookEntry> lstPBEntries = new list<PriceBookEntry>();
        priceBookSelected=true;
        
        lstPBEntries = [Select Id, Name, pricebook2.Name, product2.Name, product2.Description, product2.family 
                                            from PricebookEntry where pricebook2Id = :priceBookId  AND product2.IsActive = true and pricebook2.IsActive = true and IsActive = true];
        createPriceBookWrapperObjects(lstPBEntries);
         
    }   //  end of save
    
    public pageReference saveOpptyLineItem(){
        
        list<OpportunityLineItem>lstOpptyLineItems = new list<OpportunityLineItem>();
        for(OppLineItemWrapper objOppLineItemWrap :lstOppItems ){
            
            objOppLineItemWrap.opptyLineItem.TotalPrice = objOppLineItemWrap.premium;
            lstOpptyLineItems.add(objOppLineItemWrap.opptyLineItem);
        }
        
        if(lstOpptyLineItems.size() > 0){
            
            insert lstOpptyLineItems;
           
        }
        
        
// Rahul Mehta Commented below two lines for INC00019824 - SF1 issue
       // pageReference page = new pageReference('/'+ opp.Id);
       // return page;
        return Null;
    }
    
    public void cancel(){
        
    }   //  end of cancel
    
    public void searchProducts(){
        list<PriceBookEntry> lstPBEntries = new list<PriceBookEntry>();
        system.debug('Pricebook Id is'+pricebookId);
        string likeStr = '%'+ keyword +'%';
        lstPBEntries = [SELECT Id, Name, pricebook2.Name, product2.Name, product2.Description, product2.family 
                                            FROM PricebookEntry 
                                            WHERE pricebook2Id = :priceBookId 
                                              AND product2.Name like :likeStr
                                              AND product2.IsActive = true ];
        createPriceBookWrapperObjects(lstPBEntries);
        
    }   //  end of searchProducts
    
    public void selectProducts(){
        lstOppItems = new list<OppLineItemWrapper>();
         system.debug('*****lstPriceBooks********'+lstPriceBooks);
        for(PriceBookWrapper objWrapper : lstPriceBooks){
            if(objWrapper.isChecked){
                lstOppItems.add(new OppLineItemWrapper(objWrapper.objPriceBook.Product2.Name, opp.Id, objWrapper.objPriceBook.Id));
                
                productSearched=true;
            }
        }   //  end of for-each Wrapper
    }   //  end of selectProducts

    private void getPriceBookOptions(){
        //Id profileId = userInfo.getProfileId();
        
        
        system.debug('****inside getPriceBookOptions method*****');
        Id roleId = userInfo.getUserRoleId();
        string priceBookName = '';
        system.debug('****inside getPriceBookOptions method1*****');
        string roleName = [SELECT Id, Name FROM UserRole WHERE Id =:roleId].Name;
        system.debug('****inside getPriceBookOptions method2*****');
        //List<SF1_Role_Pricebook__c> mcs = SF1_Role_Pricebook__c.getall().values();
        for(SF1_Role_Pricebook__c cs : SF1_Role_Pricebook__c.getall().values()){
        system.debug('****inside for loop for custom setting*****');
            if(cs.Role__c == roleName){
                priceBookName = cs.PriceBook__c;
                
                system.debug('****inside if block for custom setting*****'+priceBookName );
            }
        }
        //SF1_PriceBook_Profile__c cs = SF1_PriceBook_Profile__c.getInstance(profileId);
        
        
        list<string> setPriceBookName = priceBookName.split(',');
        
        lstPriceBookOptions = new List<SelectOption>();
         system.debug('****setPriceBookName line 177 *****'+setPriceBookName  );
        for(Pricebook2 objPriceBook : [SELECT Id, Name FROM Pricebook2 WHERE Name =:setPriceBookName]){
            lstPriceBookOptions.add(new SelectOption(objPriceBook.Id, objPriceBook.Name));
            system.debug('****objPriceBookline 180*****'+objPriceBook);
        }
         system.debug('****lstPriceBookOptions line 182*****'+lstPriceBookOptions);
         system.debug('****Pricebook Id is line 183*****'+pricebookId);
    }   //  end of getPriceBookOptions
    
    private void setProductSearchLists(){
        
        lstFilterFields = new List<SelectOption>();
        lstFilterFields.add(new SelectOption('',' --NONE-- '));
        lstFilterFields.add(new SelectOption('price_book_name','Price Book Name'));
        lstFilterFields.add(new SelectOption('active','Active (Price Book)'));
        lstFilterFields.add(new SelectOption('product_name','Product Name'));
        lstFilterFields.add(new SelectOption('product_code','Product Code'));
        lstFilterFields.add(new SelectOption('product_family','Product Family'));
        
        
    }   //  end of setProductSearchLists
    
    private void createPriceBookWrapperObjects(list<PriceBookEntry> lstPBEntries){
        lstPriceBooks = new list<PriceBookWrapper>(); 
        
        for(PriceBookEntry objPB : lstPBEntries){
            lstPriceBooks.add(new PriceBookWrapper(false, objPB));
        }   //  end of for-each
    }   //  end of createPriceBookWrapperObjects
    
    class PriceBookWrapper{
        public boolean isChecked { get; set; }
        public PriceBookEntry objPriceBook { get; set; }
        
        public PriceBookWrapper(){
            isChecked=false;
        }
        
        public PriceBookWrapper(boolean pIsChecked, PriceBookEntry pPriceBook){
            isChecked = pIsChecked;
            objPriceBook = pPriceBook;
        }
    }   //  end of class
    
    class OppLineItemWrapper{
        public decimal premium { get; set; }
        public string productName { get; set; }
        public OpportunityLineItem opptyLineItem {get;set;}
        
        public OppLineItemWrapper(string pProductName, Id OpportunityId, Id pPriceBookEntryId){
            
            productName = pProductName;
            system.debug('*****product name****'+productName );
            opptyLineItem = new OpportunityLineItem(OpportunityId = OpportunityId, PriceBookEntryId = pPriceBookEntryId);
            
        }
        
    }   //  end of class
    
}   //  end of SF1AddProductCC

Test class
@isTest (SeeAllData = true)
private class TestSF1AddProductCC {
    
    static Account objAcc;
    static Opportunity objOpp;
    static Profile objProfile=null;
    static UserRole objRole=null;
    static User objUser=null;
    private static Product2  oProd;
    private static PricebookEntry oPBE;
    
    
    static ApexPages.StandardController stdController=null;
    
    
    static testMethod void ZoneTestMethod(){
        User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        
        System.runAs (thisUser){
            objProfile = [SELECT Id, Name FROM Profile WHERE Name='GVWS Sales Profile'];
            objRole = [SELECT Id, Name FROM UserRole WHERE Name='Executive Vice President' LIMIT 1];
            objUser = new User(FirstName = 'TestFirst',  
                               LastName = 'TestLast',
                               Username = 'TestFirst.TestLast' + '@testing.com',
                               CommunityNickname = 'testlast',
                               IsActive = true,
                               UserRoleId = objRole.Id,
                               Email = 'testuser@testing.com', 
                               Alias = 'tusr', 
                               TimeZoneSidKey = 'America/New_York' , 
                               LocaleSidKey = 'en_US', 
                               EmailEncodingKey = 'UTF-8', 
                               ProfileId = objProfile.Id, 
                               LanguageLocaleKey = 'en_US',
                               EBS_Division__c = 'Other',
                               EBS_Channel__c = 'Other'
                               );
            
            insert objUser;           
            
            //PermissionSet ps = [SELECT ID From PermissionSet WHERE Name = 'GVWS_Zone_Permission_Set'];
            //insert new PermissionSetAssignment(AssigneeId = objUser.id, PermissionSetId = ps.Id );
            PermissionSet psZONEGVWS = [SELECT Id FROM PermissionSet WHERE Name = 'GVWS_Zone_Permission_Set'];
          
            //Assign the above gvwsusr inserted user for the above Permission Set.
            PermissionSetAssignment psa = new PermissionSetAssignment();
            psa.AssigneeId = objUser.Id;
            psa.PermissionSetId = psZONEGVWS .Id;
        
            insert psa;
        }
        System.RunAs(objUser){
             test.startTest();
             
             List<Account> accList = new List<Account>();
             Id recId =[select id from recordtype where name = 'GVWS Employer'].id;
         
            
             objAcc = new Account(Name='Test Account',
                                  RecordtypeId=recId, 
                                  Type = 'Prospect', 
                                  ownerid = objUser.id
                                  );  
             
             insert objAcc ;
       
             
  /*   //   }
           
   // }
     //    static testMethod  void ZoneTestMethod(){ 
             //User u= [Select id,name,email,profile.name from user where lastname = 'TestLast'];
        //    User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        
       //      system.debug('*****u*****'+u);
         //   System.RunAs(thisUser) {
         //  List<Account> accList1 = [Select id from account];*/
            
            Id recOppId =[select id from recordtype where name ='GVWS Zone Opportunity'].id;
  //        system.debug('*******objrecOppIdAcc*****'+recOppId);
                objOpp = new Opportunity(Name='Test Opp',
                                     ownerid = objUser.id,
                                       AccountId=objAcc.id,
                                        //Market_Segment__c='RM',
                                       // Distribution_Channel__c='Broker',
                                        Direct__c = true,
                                        CloseDate=System.today(),
                                        StageName='Submitted',
                                        recordtypeId =  recOppId 
                                        );
               
          //  oppList.add(objOpp);
          system.debug('*******objOpp*****'+objOpp);
               // system.debug('*******objAcc.id*****'+objAcc.id);
            insert objOpp;
           system.debug('*******objOpp*****'+objOpp); 
            
           test.stopTest();
            stdController = new ApexPages.StandardController(objOpp); 
            SF1AddProductCC ext = new SF1AddProductCC(stdController);
             
             
        }
        
    }
    static testMethod  void NATestMethod(){ 
            User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        
        System.runAs (thisUser){
            objProfile = [SELECT Id, Name FROM Profile WHERE Name='GVWS Sales Profile'];
            objRole = [SELECT Id, Name FROM UserRole WHERE Name='Executive Vice President' LIMIT 1];
            objUser = new User(FirstName = 'TestFirst',  
                               LastName = 'TestLast',
                               Username = 'TestFirst.TestLast' + '@testing.com',
                               CommunityNickname = 'testlast',
                               IsActive = true,
                               UserRoleId = objRole.Id,
                               Email = 'testuser@testing.com', 
                               Alias = 'tusr', 
                               TimeZoneSidKey = 'America/New_York' , 
                               LocaleSidKey = 'en_US', 
                               EmailEncodingKey = 'UTF-8', 
                               ProfileId = objProfile.Id, 
                               LanguageLocaleKey = 'en_US',
                               EBS_Division__c = 'Other',
                               EBS_Channel__c = 'Other'
                               );
            
            insert objUser;
            
            //PermissionSet ps = [SELECT ID From PermissionSet WHERE Name = 'GVWS_Zone_Permission_Set'];
            //insert new PermissionSetAssignment(AssigneeId = objUser.id, PermissionSetId = ps.Id );
            PermissionSet psZONEGVWS = [SELECT Id FROM PermissionSet WHERE Name = 'GVWS_National_Accounts_Permission_Set'];
          
            //Assign the above gvwsusr inserted user for the above Permission Set.
            PermissionSetAssignment psa = new PermissionSetAssignment();
            psa.AssigneeId = objUser.Id;
            psa.PermissionSetId = psZONEGVWS .Id;
        
            insert psa;
        }
        System.RunAs(objUser){
             test.startTest();
             List<Account> accList = new List<Account>();
             Id recId =[select id from recordtype where name = 'GVWS Employer'].id;
         
            
             objAcc = new Account(Name='Test Account',
                                  RecordtypeId=recId, 
                                  Type = 'Prospect', 
                                  ownerid = objUser.id
                                  );  
             
             insert objAcc ;
       
             
  /*   //   }
           
   // }
     //    static testMethod  void ZoneTestMethod(){ 
             //User u= [Select id,name,email,profile.name from user where lastname = 'TestLast'];
        //    User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        
       //      system.debug('*****u*****'+u);
         //   System.RunAs(thisUser) {
         //  List<Account> accList1 = [Select id from account];*/
            
            Id recOppId =[select id from recordtype where name ='GVWS National Accounts Opportunity'].id;
  //        system.debug('*******objrecOppIdAcc*****'+recOppId);
                objOpp = new Opportunity(Name='Test Opp',
                                     ownerid = objUser.id,
                                       AccountId=objAcc.id,
                                        //Market_Segment__c='RM',
                                       // Distribution_Channel__c='Broker',
                                        Direct__c = true,
                                        CloseDate=System.today(),
                                        StageName='Submitted',
                                        recordtypeId =  recOppId 
                                        );
               
          //  oppList.add(objOpp);
          system.debug('*******objOpp*****'+objOpp);
               // system.debug('*******objAcc.id*****'+objAcc.id);
            insert objOpp;
           system.debug('*******objOpp*****'+objOpp); 
           test.stopTest();
            stdController = new ApexPages.StandardController(objOpp); 
            SF1AddProductCC ext = new SF1AddProductCC(stdController);
             
             
        }
      
    }
static testMethod void CustomTestMethod(){
        User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
        
        System.runAs (thisUser){
            objProfile = [SELECT Id, Name FROM Profile WHERE Name='GEB Australia Marketing'];
            objRole = [SELECT Id, Name FROM UserRole WHERE Name='Australia Head of Sales and Pricing' LIMIT 1];
            objUser = new User(FirstName = 'TestFirst',  
                               LastName = 'TestLast',
                               Username = 'TestFirst.TestLast' + '@testing.com',
                               CommunityNickname = 'testlast',
                               IsActive = true,
                               UserRoleId = objRole.Id,
                               Email = 'testuser@testing.com', 
                               Alias = 'tusr', 
                               TimeZoneSidKey = 'America/New_York' , 
                               LocaleSidKey = 'en_US', 
                               EmailEncodingKey = 'UTF-8', 
                               ProfileId = objProfile.Id, 
                               LanguageLocaleKey = 'en_US',
                               EBS_Division__c = 'Other',
                               EBS_Channel__c = 'Other'
                               );
            
            insert objUser;           
            
            //PermissionSet ps = [SELECT ID From PermissionSet WHERE Name = 'GVWS_Zone_Permission_Set'];
            //insert new PermissionSetAssignment(AssigneeId = objUser.id, PermissionSetId = ps.Id );
           // PermissionSet psZONEGVWS = [SELECT Id FROM PermissionSet WHERE Name = 'GVWS_Zone_Permission_Set'];
          
            //Assign the above gvwsusr inserted user for the above Permission Set.
           // PermissionSetAssignment psa = new PermissionSetAssignment();
           // psa.AssigneeId = objUser.Id;
           // psa.PermissionSetId = psZONEGVWS .Id;
        
           // insert psa;
        }
        System.RunAs(objUser){
             test.startTest();
             
             List<Account> accList = new List<Account>();
             Id recId =[select id from recordtype where name = 'GEB Australia Employer'].id;
         
            
            objAcc = new Account(Name='Test Australia',
                                  RecordtypeId=recId, 
                                  Type = 'Prospect',
                                 ownerid = objUser.id
                                  );  
             
             insert objAcc ;
       
             
 
            
           Id recOppId =[select id from recordtype where name ='GEB Australia Employer Opportunity'].id;
  //Account acc= [select id,name from account where member__c];
               objOpp = new Opportunity(Name='Test Opp',
                                     ownerid = objUser.id,
                         //            AccountId=objAcc.id,
                                     Market_Segment__c = 'Local',
                                     Business_Type__c = 'Pooled',
                                     //  Solution_Type__c = 'Captive',
                                    //   Type = 'Prospect',
                                    //   Member__c = objAcc.id,
                                     type = 'New Business',
                                     Type_Of_Quote__c = 'Direct',
                                       Effective_Date__c = System.today(),
                                       Due_Date__c = System.Today(),
                                      //  Direct__c = true,
                                        CloseDate=System.today(),
                                        Quote_Received_Date__c = System.Today(),
                                        Super_Ordinary__c = 'Ordinary',
                                        StageName='Target'
                                       // recordtypeId =  recOppId 
                                      
                                        );
               
          //  oppList.add(objOpp);
          system.debug('*******objOpp*****'+objOpp);
               // system.debug('*******objAcc.id*****'+objAcc.id);
            insert objOpp;
           system.debug('*******objOpp*****'+objOpp); 
             Id roleId = userInfo.getUserRoleId();
             string roleName = [SELECT Id, Name FROM UserRole WHERE Id =:roleId].Name;
           test.stopTest();
            stdController = new ApexPages.StandardController(objOpp); 
            SF1AddProductCC ext = new SF1AddProductCC(stdController);
             
             
        }
        
    }
   
     /*    static testMethod void testConstructor() {
        setup();
        system.runAs(objUser){
            Test.startTest();
            
            
            
            SF1AddProductCC ext = new SF1AddProductCC(stdController);
            
            Test.stopTest();
        } 
         }*/
  
    
        
    
    
    
    
}   //  end of TestSF1AddProductCC

I am facing problem with code coverage . Till now the coverage is 50%(51/101) . Can anyone help with this
pconpcon
Since writing a test class to cover all of the facets of this class is not something that anyone on here will do for you, I can give you some pointers and hopefully get you started.  I would recommend that you do some reading on testing [1] [2] [3] [4] to get a better understanding.  Each of your individual tests should only tests one specific portion of you class (ie a constructor test, sendEmail test, contactSelected test, etc).  You should also have both a postitive (everything works perfectly) and a negative (things are not right) test.

Each test should follow the following structure:
  • Setup of test data. This includes creation of any data needed by your class.  Account, Contacts etc
  • Starting the test. This is calling Test.startTest() to reset the governor limits
  • Calling your class / method
  • Stopping the test.This is calling Test.stopTest() to reset the governor limits and allow for any async jobs to finish
  • Asserting that your changes have worked
    • If you have inserted/updated/deleted data, you need to query for the updates
    • Run System.assert, System.assertEquals, System.assertNotEquals to verify that you got the correct data back
Also, unless you absolutely know that you need the seeAllData for your test, you should never use it.

If you have any specific problems with your tests, feel free to create a new post with the part of the class you are trying to test and your current test method, and you will more likely get a better response then asking for someone to essentially write an entire test class for you.

[1] http://http://www.sfdc99.com/2013/05/14/how-to-write-a-test-class/
[2] http://pcon.github.io/presentations/testing/
[3] http://blog.deadlypenguin.com/blog/2014/07/23/intro-to-apex-auto-converting-leads-in-a-trigger/
[4] http://blog.deadlypenguin.com/blog/testing/strategies/
Sarthak Bajaj 14Sarthak Bajaj 14
Hi pcon,
           Asking for complete test class was never my intention. The class was already having 50% coverage without any error. I just wanted to proceed further as i was not able to make out how to cover the rest block and what i was missing to cover that.
Anyhow i managed to cover 83% as of now. And thanks for the links provided, i will definately go through these links. :)