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
Darkangel8Darkangel8 

Need help to write test class

I am new to salesforce. Please help me to write the test class for below method-

public list<string> getZipCode( string  searchText ){
        list<string> teriNames = new list<string>();
        list<Zip_Code__c> ziplist = [Select Id, Name, BU__c, Country__c,Territory_Code__c, Territory_Name__c from Zip_Code__c where name =: searchText];
        for(Zip_Code__c zip : ziplist ){
            if(zip.Territory_Name__c != null){
                teriNames.add(zip.Territory_Name__c);  
                
            }
        }        
        
        return teriNames ;
    }
Raj VakatiRaj Vakati
try this
@isTest
private class ZipCodeTestClass {
    
    
    @isTest static void zipTestCode() {
       
	   Zip_Code__c zip = new Zip_Code__c() ;
	   zip.Name ='Demo';
	   zip.BU__c ='Demo';
	   zip.Country__c ='USA';
	   zip.Territory_Code__c ='USA';
	   zip.Territory_Name__c  ='USA';
	   insert zip ;
	   YOURCLASSSNAME cls = new YOURCLASSSNAME();
	   cls.getZipCode('Demo');
	   
	   
    }
      
}

 
Darkangel8Darkangel8
Hi Raj,

Thanks for ur help. But the coverage is still below 75%
 
Raj VakatiRaj Vakati
Which lines are not covering ..?? give me complete class 
Darkangel8Darkangel8
Hi Raj, Below is my apex class to display sales rep data based on account number and zipcode value entered in search box-->

public class TMRRepLookupVersionCon {
   
    public string SearchType{get;set;}
    public string searchText{get;set;}
    public List<Zip_Code__c> zips {get;set;}
    //public list<user> users{get;set;}
    public boolean show{get;set;} 
    public boolean NoRecords{get;set;}
    public list<UserDetails> udetails{get;set;}
    // constructor 
    public TMRRepLookupVersionCon(){
        show =false;
        NoRecords =false;
        searchType ='zip';
    }   
    
    /**
*  @description : This method is used to display the search type Check box 
*/
    public List<SelectOption> getSearchTypes() {
        List<SelectOption> options = new List<SelectOption>();         
        options.add(new SelectOption('zip','Zip Code'));        
        options.add(new SelectOption('act','Account Number'));             
        return options; 
    }    
    
    /**
*  @description : This method is used to search the reps assigned to respective 
zip code or account number 
*/
    
    public void search(){
        
        // users = new list<user>();
        udetails = new list<UserDetails>();
        
        list<string> teriNames = new list<string>();
        
        if(string.isBlank(SearchType) ){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'You must select a search type.'));
            
            
        }else if (string.isBlank(searchText ) ) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'You must enter a value to search for.'));
            
            
        } else if(searchType == 'zip' && string.isNotBlank(searchText)) {
            teriNames = getZipCode(searchText);    // [Select Id, Name, BU__c, Country__c,Territory_Code__c, Territory_Name__c from Zip_Code__c where name =: searchText ];//like \'' + searchText + '%\' limit 500';
            
            
            if(!teriNames.isEmpty()){
                
                udetails =  getDetails(teriNames);
            }
        }
        else{
            list<string> zipcode= new list<string>();
            list<string> territoryNames = new list<string>();
            if(searchType == 'act' && string.isNotBlank(searchText) ){
                if(searchText.length() == 10){
                    for(account ac: [select id, billingpostalcode,Account_No__c,Non_Acute__c,Territory_Name_RC_IS_Value__c,Territory_Name_Diagnostics_Value__c,Territory_Name_OCC_Value__c,Territory_Name_RC_Value__c,Territory_Name_Ventilation_Value__c,Territory_Name_Consumables__c from account where Account_No__c =:searchText limit 1]){  
                        //  zipcode.add(ac.billingpostalcode);
                      
                        if(ac.Non_Acute__c){
                           
                            if(ac.Territory_Name_RC_IS_Value__c!= null){
                               
                                territoryNames.add(ac.Territory_Name_RC_IS_Value__c);
                                
                            }
                            
                        }else{
                            if(ac.Territory_Name_Diagnostics_Value__c!= null){
                                territoryNames.add(ac.Territory_Name_Diagnostics_Value__c);
                            }
                            if(ac.Territory_Name_OCC_Value__c != null){
                                territoryNames.add(ac.Territory_Name_OCC_Value__c);
                            }
                            
                            if(ac.Territory_Name_Ventilation_Value__c != null){
                                territoryNames.add(ac.Territory_Name_Ventilation_Value__c );
                            }
                            if(ac.Territory_Name_Consumables__c != null){
                                territoryNames.add(ac.Territory_Name_Consumables__c );
                                }
                            
                        }
                    }
                }
                if(searchText.length() <= 8){
                    for(Account_Cross_Reference__c acfs : [SELECT Enterprise_Account_Number__c,SFDC_Account_ID__c,SFDC_Account_ID__r.Non_Acute__c,SFDC_Account_ID__r.Territory_Name_RC_IS_Value__c,SFDC_Account_ID__r.billingpostalcode,
                                                           SFDC_Account_ID__r.Territory_Name_Diagnostics_Value__c,SFDC_Account_ID__r.Territory_Name_OCC_Value__c,
                                                           SFDC_Account_ID__r.Territory_Name_RC_Value__c,SFDC_Account_ID__r.Territory_Name_Ventilation_Value__c FROM Account_Cross_Reference__c WHERE ERP_Account_Number__c =:searchText AND ERP_System__c = 'SAP - US' limit 1]){
                                                               if(acfs .SFDC_Account_ID__r.Non_Acute__c){
                                                                   if(acfs.SFDC_Account_ID__r.Territory_Name_RC_IS_Value__c!= null){
                                                                       territoryNames.add(acfs.SFDC_Account_ID__r.Territory_Name_RC_IS_Value__c);
                                                                   }
                                                                   
                                                                   
                                                               }else{
                                                                   if(acfs.SFDC_Account_ID__r.Territory_Name_Diagnostics_Value__c!= null){
                                                                       territoryNames.add(acfs.SFDC_Account_ID__r.Territory_Name_Diagnostics_Value__c);
                                                                   }
                                                                   if(acfs.SFDC_Account_ID__r.Territory_Name_OCC_Value__c != null){
                                                                       territoryNames.add(acfs.SFDC_Account_ID__r.Territory_Name_OCC_Value__c);
                                                                   }
                                                                   
                                                                   if(acfs.SFDC_Account_ID__r.Territory_Name_Ventilation_Value__c != null){
                                                                       territoryNames.add(acfs.SFDC_Account_ID__r.Territory_Name_Ventilation_Value__c );
                                                                   }
                                                                   
                                                               }
                                                               
                                                               
                                                           } 
                    
                } 
                
                
                if(!territoryNames.isEmpty()){
                    udetails =  getDetails(territoryNames);
                    
                }
            }
            
        }
        system.debug(Apexpages.hasMessages());
        if(!udetails.isEmpty()){
            
            show = true;            
            
        }else{
            show = false;
            
        }
        if( Apexpages.hasMessages() ){
            NoRecords = false;
            
        }else{
            NoRecords = true ;
            
        }
        
    }
    
    /**
*  @description : This method is used to return the list territory names based on zipe code  
*/
    
    public list<string> getZipCode( string  searchText ){
        list<string> teriNames = new list<string>();
        list<Zip_Code__c> ziplist = [Select Id, Name, BU__c, Country__c,Territory_Code__c, Territory_Name__c from Zip_Code__c where name =: searchText];
        for(Zip_Code__c zip : ziplist ){
            if(zip.Territory_Name__c != null){
                teriNames.add(zip.Territory_Name__c);  
                
            }
        }        
        
        return teriNames ;
    }
    
    /**
*  @description : This method is used to return the list users assigned to zipcode or account number 
*/ 
    
    Public list<UserDetails> getDetails(list<string> teriNames){
        set<id> teryIds = new set<id>();
        Map<id,Territory2> territorMap = new Map<id,Territory2>();
        Map<id,id> UserterriMap = new Map<id,id>();
        if(!teriNames.isEmpty()){
            
            for(Territory2 t:[SELECT id,DeveloperName,Name,Territory_No__c FROM Territory2 where Name IN : teriNames]){
               
                teryIds.add(t.id);
                territorMap.put(t.id,t); 
            }  
        }
        set<Id> userIds = new set<id>();
        if(!teryIds.isEMpty()){
            for(UserTerritory2Association  Usert:[SELECT id,UserId,Territory2Id FROM UserTerritory2Association where isActive=true  and territory2id IN : teryIds ]){
                userIds.add(Usert.UserId );
                UserterriMap.put(Usert.UserId ,Usert.Territory2Id);
                  
            }    
        }
        
        if(!userIds.isEmpty()){
            
            for(user u:[select id, name ,phone,email, Manager.Name, Manager.Email, Manager.Phone, Business_Unit__c from user where id IN : userIds and isactive= true ORDER BY Business_Unit__c]){
                //users.add(u);
               
                UserDetails ud = new UserDetails();
                ud.usr = u;
                if(UserterriMap.containskey(u.id)){
                    Id terrritoryId = UserterriMap.get(u.id); 
                    
                    ud.teriName =  territorMap.get(terrritoryId).name;
                }
                udetails.add(ud);  
            }  
        }
        return udetails; 
    }
    
    public class UserDetails{
        public user usr{get;set;}
        public string teriName{get;set;}    
    }
}
Raj VakatiRaj Vakati
Can u give me which lines are not covering in screenshot?
Darkangel8Darkangel8
User-added image
User-added image

The getDetails method is also showing red lines. Currently the code coverage is 69%
Andrew GAndrew G
The coverage is down because you don't have tests which interrogate each IF statement.

if you have a line :
if(ac.Territory_Name_Diagnostic_Value__c != null ) {
Then in you test class you will need to populate that value in the test data
example
Zip_Code__c zip = new Zip_Code__c() ;
	   zip.Name ='Demo';
	   zip.BU__c ='Demo';
	 zip.Territory_Name_Diagnostics_Value__c = 'dummy value';
///and so on
you will need to do the same for each IF statement.

AND THEN
where you have a IF ... ELSE statement, you will need a different test method for each branch of the statements
@isTest static void zipCode_nonAcuteTest() {
	   Zip_Code__c zip = new Zip_Code__c() ;
	   zip.Name ='Demo';
	   zip.BU__c ='Demo';
       zip.Non_Acute__c = 'true'

//other stuff

 @isTest static void zipCode_AcuteTest() {
	   Zip_Code__c zip = new Zip_Code__c() ;
	   zip.Name ='Demo';
	   zip.BU__c ='Demo';
       zip.Non_Acute__c = 'false'

///and so on

I like giving descriptive names to my test methods, so i makes sense at a glance to why the test may have failed. as opposed to ZipTestMethod_1, ZipTestMethod_2,..etc

Regards
Andrew 

 
Andrew GAndrew G
Oh.... and use ASSERTS in your tests

How else do you know that the test actually worked or that your code actually works?
Darkangel8Darkangel8
Hi Anderw,

We have a vf page where if I enter any account number or zipcode it display the sales reps related to that value. But currently we are getting wrong inputs so we need to update the code. 
Darkangel8Darkangel8
Below is the test class I wrote:

@istest
public class TMReplookupversionconTest {
    
    static TestMethod void testSampleSearch(){
        // new account creation
        Account acc = new Account();
        acc.Name='test';
        acc.Account_No__c='5000000000';
        acc.billingpostalcode='54561';
        //acc.Owner.name=u.Name;
             insert acc;
        // Account_Cross_Reference__c creation 
        Account_Cross_Reference__c acr = new Account_Cross_Reference__c();
        acr.Name = 'TestAcR';
        acr.SFDC_Account_ID__c = acc.id;
        acr.Source_ERP_System__c = 'ECCHQ';
        acr.ERP_Account_Number__c = '12345678';     
        acr.Enterprise_Account_Number__c ='5000000000';
        acr.ERP_System_Name__c = 'MEDI';
        insert acr;
        // new zip code creation 
   
        Zip_Code__c zipobj = new Zip_Code__c ();
        zipobj.name='54561';
        zipobj.BU__c='Diagnostics';
        zipobj.Country__c='us';
        zipobj.Territory_Code__c='123';
        zipobj.Territory_Name__c='Operative Care Consumables Inside Sales Southwest';
        
        insert zipobj;  
        TMRRepLookupVersionCon myclass=new TMRRepLookupVersionCon();
        myclass.zips = new list<Zip_Code__c>();
        myclass.getSearchTypes();
        myclass.SearchType = 'zip';
        myclass.searchText = '54561';  
        myclass.search();           
        myclass.SearchType = 'act';
        myclass.searchText = '5000000000';        
        myclass.search();
         myclass.SearchType = 'act';
        myclass.searchText = '12345678';        
        myclass.search();
    }      
}