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
Jyosi jyosiJyosi jyosi 

Test Class for the Standard Controller and Extension

Hello Everyone ,

I am trying to write the test class i am getting the code coverage of 34 % i writing the first time the test class.The bold part of code is not getting covered
it would be great if you can help.
Visual force Page
<apex:page standardController="case" extensions="GlobalComplaintExt" tabStyle="Case" id="myPage" showHeader="False">
<!--<apex:pageMessages id="MsgId" ></apex:pageMessages>-->

<script>
function handleEnter (field, event) {
        var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
        if (keyCode == 13) {
            var i;
            for (i = 0; i < field.form.elements.length; i++)
                if (field == field.form.elements[i])
                    break;
            i = (i + 1) % field.form.elements.length;
            field.form.elements[i].focus();
            return false;
        }
        else
        return true;
    }      


</script>

<apex:form id="myForm">
           <apex:pageBlock id="block1" title="Complaint Details" >
        <apex:pageMessages id="MsgId" ></apex:pageMessages>
        <apex:outputPanel >
            <apex:pageBlockSection title="Complaint Details" collapsible="true" id="section1" columns="2">
               <apex:outputField value="{!com.Contact.Name}"/>
               <apex:outputField value="{!com.contact.AccountId}"/>
                     </apex:pageBlockSection>
         
         <!--Replacement / Order Section  -->    
            
      <apex:pageBlockSection title="Replacement/Order Section" collapsible="true"  >
            <apex:inputField value="{!com.Replacement_Product__c}"  onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.Credit__c}" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.Replacement_Product_Quantity__c }" onkeypress="return handleEnter(this, event)" />
            <apex:inputField value="{!com.Credit_Note_Number__c}" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.DE_Replacment_Unit_of_Measure__c}" onkeypress="return handleEnter(this, event)"/>
            <br></br>
            <apex:inputField value="{!com.Replacement_Order_Number__c}" onkeypress="return handleEnter(this, event)"/>
            <br></br>
            <apex:inputField value="{!com.Replacement_Lot_Number__c}" onkeypress="return handleEnter(this, event)"/>
             <br></br>
            <apex:inputField value="{!com.Replacement_Order__c}" onkeypress="return handleEnter(this, event)"/>
            
        </apex:pageBlockSection>

        
        <!--  Claims Handling Section -->
        
        <apex:pageBlockSection title="Claims Handling" collapsible="true"  id="section2">
            <apex:inputField value="{!com.Claim_for_Damages__c}" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.Type_of_damage__c }" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.DE_Period_of_record_keeping__c}"   id="otherTerm" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.Apology_Letter__c }" onkeypress="return handleEnter(this, event)" />
            <apex:inputField value="{!com.Damage_Compensation_form_sent__c }" onkeypress="return handleEnter(this, event)"/>
            <apex:inputField value="{!com.Send_flowers__c }"   rendered="{!com.Country__c != "Denmark"}" id="textpop" onkeypress="return handleEnter(this, event)" />
            <apex:inputField value="{!com.PM_informed__c}"     rendered="{!com.Country__c != "Denmark"}"  id="textpop1" onkeypress="return handleEnter(this, event)" />
       </apex:pageBlockSection>

    </apex:outputPanel>
                
    <apex:pageblockbuttons >
    <apex:commandbutton action="{!SaveItem}" value="Save As Draft" reRender="MsgId" />
    <apex:commandbutton action="{!cancel}" value="Cancel" />
     
   </apex:pageblockbuttons>
   </apex:pageBlock>
           
</apex:form>

</apex:page>

Apex Class

global class GlobalComplaintExt
{
        private List<String> fieldErrors = new List<String>();
        public final Contact ContactName;
        private string contactID = '';
        private string complaintID = '';
      
        public Account Acct {get;set;}
        public Product2 pro {get;set;}
        public Case com{get;set;}
        PageReference MainPage;
        public GlobalComplaintExt(ApexPages.StandardController controller)
        {
                Id uid = userInfo.getUserId();
                User u = [select Id,User_Country_Location__c  from user where Id =: uid];
                com = (case)controller.getRecord();
                con = [select Id, Name,AccountId from Contact where id = :ApexPages.currentPage().getParameters().get('conId')];     
                if(con != null)
                com.contact = con;    
                if(u!=null)
                com.country__c = u.User_Country_Location__c;
        }
        public pageReference SaveItem()
        {
                    Country_code=com.Country__c;
                    Product_code=com.Entered_Product__c;
                    Country_code=com.Country__c;
                    system.debug('County_code120'+Country_code);
                    Product_code=com.Entered_Product__c;
                    system.debug('Prodcut_code125'+Product_code);
                    List<Product2> Product_codeList=[Select Id,Name,Country__c from Product2 where Name=:Product_code and Country__c=:Country_code LIMIT 1];
                    Map<string,Country_Customers__c> CountryCodes = Country_Customers__c.getAll();
                    List<Country_Customers__c> ListCountyCodes= new List<Country_Customers__c>();
                    ListCountyCodes=[Select Country_Code__c,Country__c,Cust_Number__c,Distribution_Channel__c,Division__c,Sales_Org__c from Country_Customers__c where Country_Code__c =:Country_code LIMIT 1];
                    
                    if(Product_codeList.size()>0 && Product_codeList!=null )
                       {
                            case CaseInsert = new Case();
                            CaseInsert.Product__c=Product_codeList[0].Id;
                            system.debug('CaseInsert.Product__cId142---------------'+Product_codeList[0].Id);
                            CaseInsert.Entered_Product__c=com.Entered_Product__c;
                            CaseInsert.country__c=Product_codeList[0].country__c;
                            CaseInsert.Voice_of_Customer__c=com.Voice_of_Customer__c;
                            CaseInsert.Complaint_Code__c=com.Complaint_Code__c;
                            CaseInsert.Problem_Damage_Code__c=com.Problem_Damage_Code__c;
                            CaseInsert.Samples_to_be_Sent__c=com.Samples_to_be_Sent__c;
                            CaseInsert.Replacement_Product__c=com.Replacement_Product__c;
                            CaseInsert.Replacement_Product_Quantity__c=com.Replacement_Product_Quantity__c;
                            CaseInsert.DE_Replacment_Unit_of_Measure__c=com.DE_Replacment_Unit_of_Measure__c;
                            CaseInsert.Credit__c=com.Credit__c;
                            CaseInsert.Credit_Note_Number__c=com.Credit_Note_Number__c;
                            CaseInsert.Replacement_Order__c=com.Replacement_Order__c;
                            Caseinsert.ContactId=con.id;
                            //Caseinsert.Product__c=com.Entered_Product__c;
                            CaseInsert.Replacement_Order_Number__c=com.Replacement_Order_Number__c;
                            CaseInsert.Replacement_Lot_Number__c=com.Replacement_Lot_Number__c;
                         
                            CaseInsert.Complaint_Lot2__c =com.Complaint_Lot__c;
                            CaseInsert.Complaint_Lot3__c =com.Complaint_Lot3__c;
                            CaseInsert.Complaint_Lot_Unknown__c=com.Complaint_Lot_Unknown__c;
                            CaseInsert.Normal_Usage__c=com.Normal_Usage__c;
                            CaseInsert.Actual_Usage__c=com.Actual_Usage__c;
                            
                            if(ListCountyCodes.size() > 0) {
                           
                            CaseInsert.GCS_Distribution_Channel__c=ListCountyCodes[0].Distribution_Channel__c;
                            CaseInsert.GCS_Sales_Org__c=ListCountyCodes[0].Sales_Org__c;
                            CaseInsert.GCS_Customer_Number__c=ListCountyCodes[0].Cust_Number__c;
                            CaseInsert.GCS_Divsion__c=ListCountyCodes[0].Division__c
;
                            }
                            try{
                            Country_Customers__c c = Country_Customers__c.getInstance(Country_code);
                            if(c != null){
                                CaseInsert.GCS_Customer_Number__c= c.Cust_Number__c;
                                CaseInsert.Sales_Org__c = c.Sales_Org__c;
                                CaseInsert.Distribution_Channel__c = c.Distribution_Channel__c;
                                CaseInsert.Division__c = c.Division__c;
                            }
                            insert CaseInsert;
                            pageReference p = new PageReference('/'+CaseInsert.Id);
                            p.setRedirect(true);
                            //system.debug('MainPageaftercaseinsert======'+MainPage);
                            return  p;
                            }
                            catch(Exception e){
                           // ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,e));
                            return null;

                            }
                    }
                    else if(Product_codeList.size()==0 )
                    {
                            system.debug('Line179');
                                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Product Entered is not avaliable for Country  '+Country_code+' '));
                            return null;
                    }
                    return null;
        }

      
}

Test Class

@isTest(SeeallData=true)
public class GlobalComplaintExtTest {
    public Case com{get;set;}
    static testMethod void UnitTest(){
        test.startTest();
       Account Test_Account= new Account(Name='TestAccount',Account_Type__c='ABC',Category__c='ABC');
       insert Test_Account;
       String Accountids;
       String ContactIds;
       List<Account> AccountQuery= new List<Account>();
       AccountQuery=[Select Id ,Name from Account Where Id =:Test_Account.Id];
       for(Account AccountList:AccountQuery)
       {
          Accountids= AccountList.id;
       }
       Contact Test_Contact= new Contact(LastName='ABC',firstName='ABC',Accountid=Accountids,Status__c='ABC',Sample_Shipping_City__c='ABC',Sample_Shipping_Street__c='ABC',
                                        Sample_Shipping_Zip_Postal_Code__c='60543',Sample_Shipping_Country__c='US',Data_Protection_Authorization__c='US',Brand__c='ABC',
                                        Type_of_Consumer__c='ABC',Source__c='ABC',Source2__c='ABC');
        insert Test_Contact;
        List<Contact> ContactQuery=[Select Id,Name from Contact Where Id=:Test_Contact.Id];
        for(Contact Cnt:ContactQuery)
        {
            ContactIds=cnt.id;
        }
        Case Caseinsert = new Case(Origin='ABC',Complaint_Source__c='ABC',Status='ABC',Voice_of_Customer__c='ABC',Entered_Product__c='ABC',GCS_Customer_Number__c='2500',GCS_Distribution_Channel__c='12'
                                   ,GCS_Divsion__c='00',GCS_Sales_Org__c='61',ContactId=Test_Contact.Id,Country__c='US',Normal_Usage__c='1',Actual_Usage__c='2');
     
        String Product='ABC';
        String Country='US';
       List<case> accountPlans= new List<case>{};
       ApexPages.currentPage().getParameters().put('conId',Test_Contact.id);
       ApexPages.StandardController sc = new ApexPages.StandardController(Caseinsert);
       GlobalComplaintExt Global_Extension= new GlobalComplaintExt(sc);
        
        PageReference pageRef =Page.GlobalComplaint;
        pageRef.getParameters().put('id', String.valueOf(Caseinsert.Id));
        Test.setCurrentPage(pageRef);
        Product2 Test_Product= new Product2(Name='28125',country__c='AU');
        insert Test_Product;
        List<Product2> ProductQuery=[Select Id,Name,Country__c from Product2 Where NAME='28125' AND country__c='AU' LIMIT 1];
        system.debug('ProductQuery@@@@@@@'+ProductQuery.size());
        Global_Extension.SaveItem();
        if(ProductQuery.size()>0 && ProductQuery!=null )
          {
              Case InsertCases= new Case();
             //s   
              InsertCases.Product__c=ProductQuery[0].id;
             
                            InsertCases.Actual_Usage__c=com.Actual_Usage__c;
*/
              insert InsertCases;
         
        }else if(ProductQuery.size()==0){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Product Entered is not avaliable for Country  '+country+' '));
        }
        
            
        test.stopTest();
        
    
        
    }

}
 
Karthik PKarthik P
Jyosi,

Assuming that you didn't mark the entire uncovered code as bold, you would need to check if there are any rows in the database which are satisfying the condition for the SOQL query you have written below:
 
List<Product2> Product_codeList=[Select Id,Name,Country__c from Product2 where Name=:Product_code and Country__c=:Country_code LIMIT 1];

The bloded block you mentioned probably did not run because it wasn't satisfying the condition you put in the if statement
 
if(Product_codeList.size()>0 && Product_codeList!=null )
                       {

I would suggest you to remove the SeeallData=true condition from the isTest annotation. This would ensure that you don't depend upon the data which is in the org and help you to debug the code better.

All the best!

 
Jyosi jyosiJyosi jyosi
Hello Karthik,

DEBUG|ProductQueryLine 29 (Product2:{Id=01tW0000001JRVAIA4, Name=25200, Country__c=DE})
Op:Insert|Type:Case|Rows:1

I am getting the query size has 1 and has you suggested i have removed the IsSeealldata =true.
Case is ge

List<Product2> ProductQuery=[Select Id,Name,Country__c from Product2 Where NAME='25200' AND country__c='DE'  and ID=:Test_Product.id LIMIT 1];
       system.debug('ProductQueryLine 29 '+ProductQuery);
            if(ProductQuery.size()>0 || ProductQuery!=null )
          {
               Case Caseinsert1 = new Case(Origin='ABC',Complaint_Source__c='ABC',Status='ABC',Voice_of_Customer__c='ABC',Entered_Product__c='ABC',
                                           GCS_Customer_Number__c='2500',GCS_Distribution_Channel__c='12'
                                   ,GCS_Divsion__c='00',GCS_Sales_Org__c='61',ContactId=Test_Contact.Id,Country__c='DE',Normal_Usage__c='1',
                                           Actual_Usage__c='2',Credit__c=true,Problem_Damage_Code__c='1211',Samples_to_be_Sent__c='1212',Product__c=Test_Product.id);
      insert Caseinsert1;
              List<case> accountPlans= new List<case>{};
            ApexPages.currentPage().getParameters().put('conId',Test_Contact.id);
       ApexPages.StandardController sc = new ApexPages.StandardController(Caseinsert1);
       GlobalComplaintExt Global_Extension= new GlobalComplaintExt(sc);
               Global_Extension.SaveItem();
              system.debug('ProductQuery@@@@@@@'+ProductQuery.size());

I am not sure why the Save method is not covering.
Can you please help me what i am missing here.

Thanks

Regards,
Jyo
Karthik PKarthik P
Hi Jyosi,

Please check if the debug statements in the SaveItem() method are being fired. Check if the below statements are being executed.
 
system.debug('County_code120'+Country_code);
Product_code=com.Entered_Product__c;
system.debug('Prodcut_code125'+Product_code);

If yes, then try to add one more debug statement after the SOQL line as shown below:
List<Product2> Product_codeList=[Select Id,Name,Country__c from Product2 where Name=:Product_code and Country__c=:Country_code LIMIT 1];
//Debug line here
system.debug(' the size of the Product_codeList is:'+Product_codeList.size());

If you see the size as non-zero, it should enter the if block and the code should be covered. Please try and let me know.