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
rajubalajirajubalaji 

how to write a test class for if else condition and return values?

Hi evryone,

how to write test class for below code if any one know please help me  and if possible please explain me.

public String getFieldByName(ProspectUser__c prospectUser, String fieldName ){
        if(fieldName.equals('FirstName')){
                return prospectUser.FirstName__c;
            }else if(fieldName.equals('LastName')){
                return prospectUser.LastName__c;
            }else if(fieldName.equals('Gender')){
                return prospectUser.Gender__c;
            }else if(fieldName.equals('Email')){
                return prospectUser.Email__c;
            }else if(fieldName.equals('DateOfBirth')){
                return String.valueOf(prospectUser.DOB__c.format());
            }else if(fieldName.trim().equalsIgnoreCase('MemberId')){
                return prospectUser.Member_ID__c;
            }else{
                return '';
            }
    }

thanks inadvance,
raju
Best Answer chosen by rajubalaji
Kritika RajKritika Raj
I just wrote a sample code based on your code , and it is having 100% code coverage you can refer to this and do the changes required in your code and Apex class .
public class UploadController {
    public Account acc {get;set;}
    public Boolean error {get;set;}
    public String message {get;set;}
    public List<String> fieldList{get;set;} // You did not set this field public , hence it will not be visible in Test class
    
    public UploadController(ApexPages.StandardController controller) {
        acc = [select Id from Account where Id = :((Account)controller.getRecord()).Id];
    }
    
    public String getFieldByName(Contact conUser, String fieldName ){
        
        if(fieldName.equals('FirstName')){
            return conUser.FirstName;
        }
        
        else if(fieldName.equals('LastName')){
            return conUser.LastName;
        }
        else if(fieldName.equals('Email')){
            return conUser.Email;
        }
        else{
            return ' ';
        }
    }
}
 
@isTest
public class TestUploadController {
    
    static testMethod void testUploadController(){
        
        Account acc  = new Account(Name = 'Test acc');
        insert acc;
        
        Contact c = new Contact(LastName = 'Testname' , Email = 'hsdaj@sd.com' , AccountId = acc.Id);
        insert c;
        
        Test.startTest();
        
        UploadController controller = new UploadController(new ApexPages.StandardController(acc));
        controller.error = true;
        controller.message ='text';
        controller.fieldList = new List<String>{'test1','test2'};
        
        String result1 = controller.getFieldByName(c , 'FirstName');
        String result2 = controller.getFieldByName(c , 'LastName');
        String result3 = controller.getFieldByName(c , 'Email');
        String result4 = controller.getFieldByName(c , 'xyz'); //covers the last else part
   
        Test.stopTest();

   }
}

All Answers

Kritika RajKritika Raj
@isTest
public class sampleTestclass {

   @isTest
    private static void testFieldByName()  {

     ProspectUser__c prop = new ProspectUser();
    //set all the required fields
     insert prop;
    
 ClassName obj1 = new ClassName();  
  
 String result1 = obj1.getFieldByName(prop , 'FirstName');
 String result2 = obj1.getFieldByName(prop , 'LastName');
 String result3 = obj1.getFieldByName(prop , 'Gender');
 String result4 = obj1.getFieldByName(prop , 'Email');
 String result5 = obj1.getFieldByName(prop , 'DateofBirth');
 String result6 = obj1.getFieldByName(prop , 'xyz');
  //Use System.assert to verify the results.
  
}
}

You will have to satisfy all the conditions in order to cover if- else structure
Kritika RajKritika Raj
Please mark this as best answer if it clears your doubt so that others can also refer to it.
rajubalajirajubalaji
Hi Kritika Raj,

Thank you so much for quick response.but here i was have one doubt instead of "ClassName obj1 = new ClassName(); " i was getting invaild type..can u please help me how to clear that.

thanks inadvance,
Raju
Kritika RajKritika Raj
Could you share the snipper of your test class?
Kritika RajKritika Raj
Check that the class name is correct in which the following method exists. If the method is static in your class just use ClassName.MethodName and if the method is not static then call the method as shared in the above code snippet.
rajubalajirajubalaji
hi,

Apex Class:

public class UploadController {
    public Account acc {get;set;}
    public Boolean error {get;set;}
    public String message {get;set;}
    List<String> fieldList{get;set;}

public UploadController(ApexPages.StandardController controller) {
        acc = [select Id, starId__c,Enviornment_Code__c from Account where Id = :((Account)controller.getRecord()).Id];
    }

public String getFieldByName(ProspectUser__c prospectUser, String fieldName ){
        if(fieldName.equals('FirstName')){
                return prospectUser.FirstName__c;
            }else if(fieldName.equals('LastName')){
                return prospectUser.LastName__c;
            }else if(fieldName.equals('Gender')){
                return prospectUser.Gender__c;
            }else if(fieldName.equals('Email')){
                return prospectUser.Email__c;
            }else if(fieldName.equals('DateOfBirth')){
                return String.valueOf(prospectUser.DOB__c.format());
            }else if(fieldName.trim().equalsIgnoreCase('MemberId')){
                return prospectUser.Member_ID__c;
            }else{
                return '';
            }
    }

Test Class:

@isTest
public class TestUploadController {
    static testMethod void testEligibilityUploadController(){Test.startTest();
        Account acc  = getAccount_Model2();
        UploadController controller = new UploadController(new ApexPages.StandardController(acc));
        controller.error = true;
        controller.message ='text';

Test.StopTest();
   }
    static testmethod void testGetFieldByName(){
        ProspectUser__c prop = new ProspectUser__c();
        insert prop;
        
        
        String result1 = patient.getFieldByName('FirstName');
        String result2 = getFieldByName(prop , 'LastName');
        String result3 = getFieldByName(prop , 'Gender');
        String result4 = getFieldByName(prop , 'Email');
        String result5 = getFieldByName(prop , 'DateofBirth');
        String result6 = getFieldByName(prop , 'MemberId');
    }

this is the apex class and test class which i written,actually i was new to coding.so can u please help me.


Thanks Inadvance,
Raju Balaji
Kritika RajKritika Raj
Test.startTest and stopTest are used to reset governor limits . You can write your test class without it but its a good practice to use this . use this from where the test will actually start. Please try this and let me know if you face any issues.
@isTest
public class TestUploadController {
    
    static testMethod void testUploadController(){
        
        Account acc  = getAccount_Model2(); //Where is this method
        //Always use test records.
        
        Account acc = new Account();
        acc./*RequiredField1*/ = /*Test Data according to the type of the field;*/
        acc./*RequiredField2*/ = /*Test Data according to the type of the field; ..... so on*/
        
        insert acc;
        
        ProspectUser__c prop = new ProspectUser__c();
        prop./*RequiredField1*/ = /*Test Data according to the type of the field;*/
        prop./*RequiredField2*/ = /*Test Data according to the type of the field; ..... so on*/
        insert prop;
        
        Test.startTest();
        
        UploadController controller = new UploadController(new ApexPages.StandardController(acc));
        controller.error = true;
        controller.message ='text';
        
        String result1 = controller.getFieldByName('FirstName');
        String result2 = controller.getFieldByName(prop , 'LastName');
        String result3 = controller.getFieldByName(prop , 'Gender');
        String result4 = controller.getFieldByName(prop , 'Email');
        String result5 = controller.getFieldByName(prop , 'DateofBirth');
        String result6 = controller.getFieldByName(prop , 'MemberId');
        
        Test.stopTest();

   }
}

 
rajubalajirajubalaji
Hi,

i was facing issue what i need to write in requried field1.i was written like this but it was showing error.

Account acc =new Account();
        acc.FirstName = 'nMM';
        acc.LastName = 'MMM';
        acc.Gender = 'Male';
        acc.Email = 'raju+test@welldocinc.com';
        acc.DateofBirth = '1/1/1980';
        acc.Member_ID__c = '107556330459';
        insert acc;
        
        ProspectUser__c prop = new ProspectUser__c();
        prop.FirstName = 'nMM';
        prop.LastName = 'MMM';
        prop.Gender = 'Male';
        prop.Email = 'raju+test@welldocinc.com';
        prop.DateofBirth = '1/1/1980';
        prop.Member_ID__c = '107556330459';
        insert prop;

can u please help me.

Thanks Inadvance,
Raju Balaji
Kritika RajKritika Raj
Please check the type of DateofBrith field . If its Date type use 'System.today()' and if its of Date/Time Type then use 'System.now()' as test data. Also , if Member_Id__c is a lookup field , then please insert a record for the Parent Object and then use its Id in the lookup. Ex:
Account a  =  new Account();
a.Name = 'Test Account 1';
a.DateOfBirth = System.today();
insert a;

Contact c = new Contact();
c.LastName = 'Test Contact 1';
c.AccountId = a.Id;
insert c;

Data in single quotes are considered as String Type . One more thing we usually dont have FirstName and LastName field on Account object unless its a Person Account which is enabled by Salesforce on request . By default the Account is of business type in the org. 
rajubalajirajubalaji
Hi,

As per your guide lines i have written code like this.but i was not incresing cose percentage.

static testmethod void testgetFieldByName(){
        
        Account acc =new Account();
        
        ProspectUser__c prop = new ProspectUser__c();
        prop.FirstName__c = 'nMM';
        prop.LastName__c = 'MMM';
        prop.Gender__c = 'Male';
        prop.Email__c = 'raju+test@welldocinc.com';
        prop.DOB__c = System.today();
        prop.Member_ID__c = '107556330459';
        insert prop;
        
        Test.startTest();
        
        UploadController controller = new UploadController(new ApexPages.StandardController(acc));
        
        String result1 = controller.getFieldByName(prop, 'FirstName');
        String result2 = controller.getFieldByName(prop , 'LastName');
        String result3 = controller.getFieldByName(prop , 'Gender');
        String result4 = controller.getFieldByName(prop , 'Email');
        String result5 = controller.getFieldByName(prop , 'DateofBirth');
        String result6 = controller.getFieldByName(prop , 'MemberId');
        
        Test.stopTest();
        
    }
Kritika RajKritika Raj
You have not inserted the Account acc . Please set required value for Account as you did for ProspectUser__c  and insert Account. Currenlty acc is null;
Kritika RajKritika Raj
I just wrote a sample code based on your code , and it is having 100% code coverage you can refer to this and do the changes required in your code and Apex class .
public class UploadController {
    public Account acc {get;set;}
    public Boolean error {get;set;}
    public String message {get;set;}
    public List<String> fieldList{get;set;} // You did not set this field public , hence it will not be visible in Test class
    
    public UploadController(ApexPages.StandardController controller) {
        acc = [select Id from Account where Id = :((Account)controller.getRecord()).Id];
    }
    
    public String getFieldByName(Contact conUser, String fieldName ){
        
        if(fieldName.equals('FirstName')){
            return conUser.FirstName;
        }
        
        else if(fieldName.equals('LastName')){
            return conUser.LastName;
        }
        else if(fieldName.equals('Email')){
            return conUser.Email;
        }
        else{
            return ' ';
        }
    }
}
 
@isTest
public class TestUploadController {
    
    static testMethod void testUploadController(){
        
        Account acc  = new Account(Name = 'Test acc');
        insert acc;
        
        Contact c = new Contact(LastName = 'Testname' , Email = 'hsdaj@sd.com' , AccountId = acc.Id);
        insert c;
        
        Test.startTest();
        
        UploadController controller = new UploadController(new ApexPages.StandardController(acc));
        controller.error = true;
        controller.message ='text';
        controller.fieldList = new List<String>{'test1','test2'};
        
        String result1 = controller.getFieldByName(c , 'FirstName');
        String result2 = controller.getFieldByName(c , 'LastName');
        String result3 = controller.getFieldByName(c , 'Email');
        String result4 = controller.getFieldByName(c , 'xyz'); //covers the last else part
   
        Test.stopTest();

   }
}
This was selected as the best answer
rajubalajirajubalaji
Hi,

Thank you so much for help.

i  have some chnages but ur guide will help me almost.
Thank you so much.