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
shinerajbshinerajb 

Unit testing of json parser

How do i do the unit testing for this.Unit testing does not go into this part. 

it is not being tested from response.getbody().

We are doing a lot of  json parsing please do help

Shine

 

************Code*******************

JSONParser parser = JSON.createParser(response.getBody());

while (parser.nextToken() != null)
{
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'total_records'))
{
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
total_records=integer.valueof(parser.getText());
// total_records=
}

 

************Code*******************

Best Answer chosen by Admin (Salesforce Developers) 
tomcollinstomcollins

You need to create a response object with a body that contains JSON with a "total_records" field.

 

How are you currently unit testing the method that contains this code?  You have to create a fake HttpResponse object, since test cases don't send HTTP requests, right?

 

If you look at the Apex documentation on Testing HTTP Callouts, it shows you how to do it.

 

All Answers

tomcollinstomcollins

You need to create a response object with a body that contains JSON with a "total_records" field.

 

How are you currently unit testing the method that contains this code?  You have to create a fake HttpResponse object, since test cases don't send HTTP requests, right?

 

If you look at the Apex documentation on Testing HTTP Callouts, it shows you how to do it.

 

This was selected as the best answer
Susan TaylorSusan Taylor
Will admit this had me stumped. The above bit of advice got me half way there.  I have a callout to the google map api in a trigger - the problem was figuring out a way for the test to reach the json parsing code -  because the 'real' callout would never occur, this section would always be skipped.  Going modular did the trick - by pulling out the callout and parsing sections and putting them in a separate class in their own methods -  I could now reach the code with a method call from the test script.