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
Alex Calder 10Alex Calder 10 

Apex Code coverage fpr this Class

I am struggleing understanding how to write test units for this class. 
 
//@RestResource(urlMapping='/Google/*') is used to tell the class that it is a REST resource used for POST GET etc
@RestResource(urlMapping='/Google/*')
global with sharing class GoogleWebHookListener {
    //HttpPost tells the method that it will be a POST method
    @HttpPost
    global static void handlePost() {
        
        //set up varibles for the Lead
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == ''){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            Lead detail = new Lead();
            detail.LastName = lastName;
            detail.FirstName = firstName;
            detail.Phone = phone;
            detail.Company = name;
            detail.Email = email;
            detail.OwnerId = '0051Q00000GrANL'; // This Id is the user Hubspot.
            insert detail;
           
            }
                                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }

}

 
Best Answer chosen by Alex Calder 10
Maharajan CMaharajan C
Hi Alex,

Please try the below test class:
 
@isTest
public class GoogleWebHookListenerTest {
    static testmethod void doPostTest(){
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/Google';
        request.httpMethod = 'POST';
        String str = '{'+ '"lead_id": "TeSter",'+'"user_column_data": ['+'{'+'"column_name": "Full Name",'+'"string_value": "FirstName LastName",'+'"column_id": "FULL_NAME"'+'},'+'{'+'"column_name": "User Phone",'+'"string_value": "+16505550123",'+' "column_id": "PHONE_NUMBER"'+'},'+'{'+'"column_name": "User Email",'+'"string_value": "test@example.com",'+'"column_id": "EMAIL"'+'},'+'{'+'"column_name": "Postal Code",'+'"string_value": "94043",'+'"column_id": "POSTAL_CODE"'+'},'+'{'+'"string_value": "Roofing",'+'"column_id": "SERVICE"'+'}'+'],'+'"api_version": "1.0",'+'"form_id": 18698608977,'+'"campaign_id": 991214827,'+'"google_key": "",'+'"is_test": true,'+'"gcl_id": "CcDdEeFfGgHhIiJjKkLl",'+'"adgroup_id": 20000000000,'+'"creative_id": 30000000000'+'}';
        request.requestBody = Blob.valueof(Str);
        
        RestContext.request = request;
        GoogleWebHookListener.handlePost();
    }
}

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Alex,

Can you please post the GoogleJsonLeadExample Class and Sample JSON here to help you.

Thanks,
Maharajan.C
Alex Calder 10Alex Calder 10
//this class sets up Properties that the JSON recieved from GoogleWebHookListener
public class GoogleJsonLeadExample {
        public string lead_id { get; set; }
        public List<userData> user_column_data { get; set; }
        public string api_version { get; set; }
        public double form_id { get; set; }
        public double campaign_id { get; set; }
        public string google_key { get; set; }
        public boolean is_test { get; set; }
        public string gcl_id { get; set; }
        public double adgroup_id { get; set; }
        public double creative_id { get; set; }

        public class userData
        {
            public string column_name { get; set; }
            public string string_value { get; set; }
            public string column_id { get; set; }


        }
}
 
'{'+ 
  '"lead_id": "TeSter",'+
  '"user_column_data": ['+
    '{'+
      '"column_name": "Full Name",'+
      '"string_value": "FirstName LastName",'+
      '"column_id": "FULL_NAME"'+
    '},'+
    '{'+
      '"column_name": "User Phone",'+
      '"string_value": "+16505550123",'+
     ' "column_id": "PHONE_NUMBER"'+
    '},'+
    '{'+
      '"column_name": "User Email",'+
      '"string_value": "test@example.com",'+
      '"column_id": "EMAIL"'+
    '},'+
    '{'+
      '"column_name": "Postal Code",'+
      '"string_value": "94043",'+
      '"column_id": "POSTAL_CODE"'+
    '},'+
    '{'+
      '"string_value": "Roofing",'+
      '"column_id": "SERVICE"'+
    '}'+
  '],'+
  '"api_version": "1.0",'+
  '"form_id": 18698608977,'+
  '"campaign_id": 991214827,'+
  '"google_key": "",'+
  '"is_test": true,'+
  '"gcl_id": "CcDdEeFfGgHhIiJjKkLl",'+
  '"adgroup_id": 20000000000,'+
  '"creative_id": 30000000000'+
'}'

 
Maharajan CMaharajan C
Hi Alex,

Please try the below test class:
 
@isTest
public class GoogleWebHookListenerTest {
    static testmethod void doPostTest(){
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/Google';
        request.httpMethod = 'POST';
        String str = '{'+ '"lead_id": "TeSter",'+'"user_column_data": ['+'{'+'"column_name": "Full Name",'+'"string_value": "FirstName LastName",'+'"column_id": "FULL_NAME"'+'},'+'{'+'"column_name": "User Phone",'+'"string_value": "+16505550123",'+' "column_id": "PHONE_NUMBER"'+'},'+'{'+'"column_name": "User Email",'+'"string_value": "test@example.com",'+'"column_id": "EMAIL"'+'},'+'{'+'"column_name": "Postal Code",'+'"string_value": "94043",'+'"column_id": "POSTAL_CODE"'+'},'+'{'+'"string_value": "Roofing",'+'"column_id": "SERVICE"'+'}'+'],'+'"api_version": "1.0",'+'"form_id": 18698608977,'+'"campaign_id": 991214827,'+'"google_key": "",'+'"is_test": true,'+'"gcl_id": "CcDdEeFfGgHhIiJjKkLl",'+'"adgroup_id": 20000000000,'+'"creative_id": 30000000000'+'}';
        request.requestBody = Blob.valueof(Str);
        
        RestContext.request = request;
        GoogleWebHookListener.handlePost();
    }
}

Thanks,
Maharajan.C
This was selected as the best answer
Alex Calder 10Alex Calder 10
WOW, that helped a ton.  I wrote one too while I waited.  I am new, thank you for your quick help.
static testMethod void validateGoogleWebHookListener(){
        
        //set up varibles for the Lead
        String jsonString = 
        '{'+ 
  '"lead_id": "TeSter",'+
  '"user_column_data": ['+
    '{'+
      '"column_name": "Full Name",'+
      '"string_value": "Alex TestCalder",'+
      '"column_id": "FULL_NAME"'+
    '},'+
    '{'+
      '"column_name": "User Phone",'+
      '"string_value": "9196803058",'+
     ' "column_id": "PHONE_NUMBER"'+
    '},'+
    '{'+
      '"column_name": "User Email",'+
      '"string_value": "test@example.com",'+
      '"column_id": "EMAIL"'+
    '},'+
    '{'+
      '"column_name": "Postal Code",'+
      '"string_value": "94043",'+
      '"column_id": "POSTAL_CODE"'+
    '},'+
    '{'+
      '"string_value": "Roofing",'+
      '"column_id": "SERVICE"'+
    '}'+
  '],'+
  '"api_version": "1.0",'+
  '"form_id": 18698608977,'+
  '"campaign_id": 991214827,'+
  '"google_key": "bakerGoogleWebHookValue",'+
  '"is_test": true,'+
  '"gcl_id": "CcDdEeFfGgHhIiJjKkLl",'+
  '"adgroup_id": 20000000000,'+
  '"creative_id": 30000000000'+
'}';
        
        String name;
        String phone;
        String email;
        String postCode;
        String firstName;
        String lastName;
        
        
        
        //try to do the JSON deserialization and Lead Creation
        //******EXAMPLE JSON AT BOTTOM*****
        try
        {
            // This gets the body of the webhook makes the body a string and sets the string to the variable 'jsonString'
            //String jsonString = RestContext.request.requestBody.toString();
            //This deserializes the JSON based on the the properties setup in the Class GoogleJsonLeadExample
            GoogleJsonLeadExample g = (GoogleJsonLeadExample)JSON.deserialize(jsonString, GoogleJsonLeadExample.class);
            
            //This tests the JSON to see if it is legit.
            if(g.google_key == 'bakerGoogleWebHookValue'){
                
                //This loops through the JSON array set up in the Class GoogleJsonLeadExample
                
               for(GoogleJsonLeadExample.userData d : g.user_column_data)
               {
                   if(d.column_name == 'Full Name')
                   {
                       //The JSON has Full Name, this breaks Full Name into First and Last Names
                        name = d.string_value;
                        List<String> names = name.split(' ');
                       	firstName = names[0];
                        lastName = names[1];
                           
                   }
                   if(d.column_name == 'User Phone')
                   {
                        phone = d.string_value;
                   }
                   if(d.column_name == 'User Email')
                   {
                        email = d.string_value;
                   }
                   if(d.column_name == 'Postal Code')
                   {
                       postCode = d.string_value;
                   }
               }
              
                //This creates the Lead                 
            List<Lead> detail = new List<Lead>();
                for (Integer i = 0; i < 10; i++){
            detail.add(new Lead(LastName = lastName + i,FirstName = firstName + i
               , Phone = phone + i, Company = name + i, Email = email +i,OwnerId = '0051Q00000GrANL' ));
            
                    }
            insert detail;
              
               map<Id, Lead> lead_map = new map<Id, Lead>();
        
        			for (Integer i = 0;i<10;++i){
                         lead_map.put(detail[i].Id,detail[i]);
        }
            System.assert([SELECT count() FROM Lead WHERE Id IN :lead_map.keySet()] == 10);
           
            }
                        
        }
        catch (DMLException e)
        {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
      
             
    }
Alex Calder 10Alex Calder 10
Serious awesome, thank you again.  I understand what you did.  Thank you again!
real docsreal docs
BUY CDC  COVID-19 REGISTERED VACCINATION RECORD CARD AT 
WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
BUY COVID19 VACCINATION RECORD CARD
BUY COVID19 VACCINATION RECORD CARD
BUY COVID19 VACCINATION RECORD CARD
BUY CDC COVID-19 CACCINATION RECORD CARD
covid19 vaccination card

BUY D.M.V DRIVER'S LICENSE ONLINE, WE PRODUCE REAL REGISTERED DMV DRIVERS LICENCE, 
YOU DON'T NEED ANY EXAMS OR TEST OKAY, MY BOSS WORKS IN THE DMV OFFICE AND HAS THE POWERS TO PRODUCE YOU A REAL REGISTERED DRIVERS LICENCE WITHIN 3 DAYS.
BUY USA EAL REGISTERED DIVERS LICENCE
BUY UK REAL REGISTERED DRIVERS LICENCE 
BUY AUSTRALIAN REAL REGISTERED DRIVERS LICENCE
BUY GERMAN REAL REGISTERED DRIVERS LICENCE AND MANY OTHER COUNTRIES
BUY COVID-19 VACCINATION RECORD CARD AT

BUY COVID19 VACCINATION RECORD CARD
BUY COVID19 VACCINATION RECORD CARD
BUY COVID19 VACCINATION RECORD CARD
BUY COVID19 VACCINATION RECORD CARD
WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
Buy covid-19 vaccine record card online without taking the vaccine

Buy covid-19 vaccine record card nline, for now, the best way to show that you have been inoculated against the corona virus is a simple white card
Buy covid-19 vaccination card online
Covid-19 vaccine record card for sale in USA
paper COVID-19 vaccination ID is a verified , physical eveidence of your individual vaccination ststus, complete with sophisticated anti counterfeit technology to ensure authenticity and peace of mind

WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
We produce verified registered cdc covid19 vaccination cards that can enable you travel or present at your job side on request, Buy regietered covid19  vaccine card at affordable prices without getting vaccinated 

GET REGISTERED JAB CARD AT AFFORDABLE PRICES, WE PRODUCE AND GIVE OUT REGISTERED COVID CARDS
BUY JAB CARDS
BUY CDC COVID-19 VACCINATION CARD
GET JAB CARD
OBTAIN JAB CARD
contact
WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
Email: realdocs78@gmail.com 


GET REGISTERED JAB CARD AT AFFORDABLE PRICES, WE PRODUCE AND GIVE OUT REGISTERED COVID CARDS
BUY JAB CARDS
BUY CDC COVID-19 VACCINATION CARD
GET JAB CARD
OBTAIN JAB CARD

WhatsApp: +1 (951) 480-4136

We produce a verified registered cdc covid-19 vaccination cards that can enable you travel or present at your job side
buy registered covid19 vaccination cards at affordable prices

WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
email....realdocs78@gmail.com
email....realdocs78@gmail.com
WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
We produce verified registered cdc covid19 vaccination cards that can enable you travel or present at your job side on request, Buy regietered covid19  vaccine card at affordable prices without getting vaccinated 
email....realdocs78@gmail.com
email....realdocs78@gmail.com
Buy covid-19 vaccine record card online without taking the vaccine

Buy covid-19 vaccine record card nline, for now, the best way to show that you have been inoculated against the corona virus is a simple white card
Buy covid-19 vaccination card online
Covid-19 vaccine record card for sale in USA
paper COVID-19 vaccination ID is a verified , physical eveidence of your individual vaccination ststus, complete with sophisticated anti counterfeit technology to ensure authenticity and peace of mind

WhatsApp: +1 (951) 480-4136
WhatsApp: +1 (951) 480-4136
Email: realdocs78@gmail.com