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
Alx MrAlx Mr 

Test Method for Google v2 reCaptcha

Hello.

Im having difficulty creating test method for the reCaptcha.

The verify() function is trigerred when Save() is called, please see bellow:
 
public PageReference save(){
       verify();
        If (verified==true){
        ....
        }

The reCapture methods perse are as follows:
 
@TestVisible private String baseUrl = 'https://www.google.com/recaptcha/api/siteverify?';
@TestVisible private String privateKey = 'MyPrivateKey';
@TestVisible public String publicKey {get { return 'MypublicKey'; }}
@TestVisible public String challenge { get {returnApexPages.currentPage().getParameters().get('recaptcha challenge');}}
@TestVisible public String response  { get {returnApexPages.currentPage().getParameters().get('g-recaptcha-response');}}
    public Boolean verified { get; set; }
    
    public void verify() {HttpResponse r = makeRequest(baseUrl, 'secret=' + privateKey +'&response='  + response +'&remoteip='  + remoteHost );
                          System.debug(r.getBody());
                          JSONParser parser = JSON.createParser(r.getBody());
                          while (parser.nextToken() != null) {
                             if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'success')) {
                                  parser.nextToken();
                                  if (parser.getBooleanValue()==true){verified =true;}else{verified = false;} }
                          }
                         }
    public PageReference reset() {return null; }
    @TestVisible private HttpResponse makeRequest(string url, string body)  {
        HttpResponse response = null;
        HttpRequest req = new HttpRequest();  
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody (body);
        try {
            Http http = new Http();
            response = http.send(req);
            System.debug('reCAPTCHA response: ' + response);
            System.debug('reCAPTCHA body: ' + response.getBody());
        } catch(System.Exception e) {
            System.debug('ERROR: ' + e);
        }
        return response;
    }  
     
    @TestVisible public String remoteHost {get {
        String ret = '127.0.0.1';
        Map<String, String> hdrs = ApexPages.currentPage().getHeaders();
        if (hdrs.get('REMOTE_ADDR')!= null)
          ret =  hdrs.get('x-original-remote-addr');
        else if (hdrs.get('X-Salesforce-SIP')!= null)
           ret =  hdrs.get('X-Salesforce-SIP');
        return ret;
    }
   }




As per suggestions on forums, particularly the resource: 
https://developer.salesforce.com/index.php?title=Adding_CAPTCHA_to_Force.com_Sites&oldid=42318
i came up to the following insertion into a test method for the function save():
 
ctr= new controllerLeadConfirmationPage();
...
string href = ctr.baseUrl ;
ctr.response = 'foo';
ctr.challenge = ctr.response;
string publick = ctr.publicKey;
string host = ctr.remoteHost;
...
ctr.save()

But still I cannot get it working:
System.NullPointerException: Attempt to de-reference a null object - line 1191 (which is  ' System.debug(r.getBody());' in the verify() function bellow)
 
public void verify() {HttpResponse r = makeRequest(baseUrl, 'secret=' + privateKey +'&response='  + response +'&remoteip='  + remoteHost );
                          System.debug(r.getBody());
                          JSONParser parser = JSON.createParser(r.getBody());
                          while (parser.nextToken() != null) {
                              if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'success')) {
                                  parser.nextToken();
                                  if (parser.getBooleanValue()==true){verified =true;}else{verified = false;} }
                          }
                         }

Please advise me how can i solve it.
sharathchandra thukkanisharathchandra thukkani
When you run the  test class you won't get the response need to hardcode the response in your case set the static variable and assign hard coded response to it  when ever you run the test class.
Alx MrAlx Mr
I see. This is what i tried 

System.assertEquals('{"success":"true"}', ctr.response.getBody());
System.assertEquals(200,ctr.response.getStatusCode());
System.assertEquals('application/json', ctr.response.getHeader('Content-Type'));

Im getting the following reject:
method does not exist/ incorrect signature:  ctr.response.getBody());