+ Start a Discussion
Abhishek Pal 33Abhishek Pal 33 

How to set variable in pageReference method in test class

Hello everyone,
I have one controller written below and while writing test class I need to set the values for the upcNumbers so that I can call the validate method.  Also I need to test the success or failure message which I have written in controller class. But I am unable to set these values can someone please help.

public pagereference validate()
    {
        
         List <String> upcNumbers = new List <String>();
     
for(String upcNo : upcNumbers){
            
            Upcs = Upcs + upcNo +'\''+ ','+'\'';
        }
        Upcs =Upcs.removeEnd('\',\'');
       
        HttpResponse response = UPCAdderUtil.validateCallout(Upcs);
}
V V Satyanarayana MaddipatiV V Satyanarayana Maddipati
Hi Abhishek,

you can't access upcNumbers and response variables in the test class, As there are restricted to that particular method. Move both of these variables to outside of your method as shown below: You can change the Private member variables to public . If it is private, TestVisible annotation is mandatory to access those private variables  in your test class.
public class YourClassName {
    
    @TestVisible private List <String> upcNumbers = new List <String>();
    @TestVisible private HttpResponse response;
    
    public pagereference validate() {
        for(String upcNo : upcNumbers) {
            
            Upcs = Upcs + upcNo +'\''+ ','+'\'';
        }
        Upcs =Upcs.removeEnd('\',\'');
        
        response = UPCAdderUtil.validateCallout(Upcs);
    }
}

Here is the Test class:
 
@isTest
private class YourClassName_Test {
    
    private static testMethod void test1() {
        YourClassName clsIns = new YourClassName(); // create Your controller Instance
        clsIns.upcNumbers  = {'str1', 'str2','str3'}; // setting the Values to the upcNumbers Variable.
        clslns.validate(); // Call the Validate Method.
        HttpResponse res = clslns.response //Contains Httpresponse.
    }   
}

By using "res" variable, you can check the success and error message in the test class.

Thanks
Satya.