Deprecated: Optional parameter $list declared before required parameter $is_script is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 21

Deprecated: Optional parameter $register declared before required parameter $footer_or_media is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 45

Deprecated: Optional parameter $register declared before required parameter $footer_or_media is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php on line 104

Deprecated: Optional parameter $expire declared before required parameter $path is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_functions.php on line 54

Deprecated: Optional parameter $depth declared before required parameter $output is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/themes/entaro/inc/classes/megamenu.php on line 155

Deprecated: Optional parameter $depth declared before required parameter $output is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/themes/entaro/inc/classes/mobilemenu.php on line 147

Deprecated: Optional parameter $args declared before required parameter $wp_customize is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/extensions/customizer/extension_customizer.php on line 583

Deprecated: Optional parameter $args declared before required parameter $wp_customize is implicitly treated as a required parameter in /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/extensions/customizer/extension_customizer.php on line 606

Warning: Cannot modify header information - headers already sent by (output started at /home1/oijoiv2f/public_html/wp-content/plugins/apus-framework/libs/redux/ReduxCore/inc/class.redux_cdn.php:21) in /home1/oijoiv2f/public_html/wp-includes/feed-rss2.php on line 8
apex test class Archives - Salesforce Next Gen https://salesforcenextgen.com/tag/apex-test-class/ Trailhead and Beyond Mon, 28 Dec 2020 19:45:53 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://salesforcenextgen.com/wp-content/uploads/2020/10/cropped-76dc0dd6-326a-4956-a412-bfdf20c7fb23_200x200-32x32.png apex test class Archives - Salesforce Next Gen https://salesforcenextgen.com/tag/apex-test-class/ 32 32 How to do JSON Parsing of a wrapper class in Salesforce https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/ https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/#comments Mon, 05 Mar 2018 06:02:34 +0000 http://www.salesforcenextgen.com/?p=1240 How to do JSON Parsing of a wrapper class in Salesforce. What is JSON Parsing? We use JSON parsing to interchange data from a web server. Data is always shared as a string from a web server To make the data understandable to our system, we do JSON Parsing, and the data becomes a JavaScript …
Continue reading How to do JSON Parsing of a wrapper class in Salesforce

The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.

]]>
JSON Parsing SalesforceHow to do JSON Parsing of a wrapper class in Salesforce.

What is JSON Parsing?

We use JSON parsing to interchange data from a web server.

Data is always shared as a string from a web server

To make the data understandable to our system, we do JSON Parsing, and the data becomes a JavaScript object.

Example of JSON Parsing.

‘{ “name”:”John”, “age”:30, “city”:”New York”}’

Use the JavaScript function JSON.parse() to convert text into a JavaScript object

var obj = JSON.parse(‘{ “name”:”John”, “age”:30, “city”:”New York”}’);

The above example is to do parsing in JavaScript, To do JSON Parsing in Salesforce we have quiet similar approach.

But first we should understand few terms before we begin the JSON parsing concept.

To convert an object into a stream of string characters is known as serialization, i. e Object -> String. Once we serialize an object we can transport it over the web server.

JSON Parsing Salesforce

To convert a stream of string into an object is known as deserialization, or simply opposite of serialization is called deserialization, normally it is a response received from a web server. String -> Object.

To simplify the process of serialization and deserialization, Salesforce has provided a whole class for this purpose, i.e. JSONParser Class.

In below a callout was made to web service and it returned a response in JSON format. Then the response is parsed to get all the totalPrice field values and get the grand total.

public class JSONParserUtil {

@future(callout=true)

public static void parseJSONResponse() {

Http httpProtocol = new Http();

HttpRequest request = new HttpRequest();

String endpoint = ‘https://docsample.herokuapp.com/jsonSample’;

request.setEndPoint(endpoint);

request.setMethod(‘GET’);

HttpResponse response = httpProtocol.send(request);

System.debug(response.getBody());

// Parse JSON response to get all the totalPrice field values.

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

Double grandTotal = 0.0;

while (parser.nextToken() != null) {

if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&

(parser.getText() == ‘totalPrice’)) {

// Get the value.

parser.nextToken();

// Compute the grand total price for all invoices.

grandTotal += parser.getDoubleValue();

}

}

system.debug(‘Grand total=’ + grandTotal);

}

}

Example: Parse a JSON String and Deserialize It into Objects, for this example we are taking a hardcoded JSON  String and the entire string is parsed into Invoice objects using the readValueAs method.

public static void parseJSONString() {

String jsonStr =

‘{“invoiceList”:[‘ +

‘{“totalPrice”:5.5,”statementDate”:”2011-10-04T16:58:54.858Z”,”lineItems”:[‘ +

‘{“UnitPrice”:1.0,”Quantity”:5.0,”ProductName”:”Pencil”},’ +

‘{“UnitPrice”:0.5,”Quantity”:1.0,”ProductName”:”Eraser”}],’ +

‘”invoiceNumber”:1},’ +

‘{“totalPrice”:11.5,”statementDate”:”2011-10-04T16:58:54.858Z”,”lineItems”:[‘ +

‘{“UnitPrice”:6.0,”Quantity”:1.0,”ProductName”:”Notebook”},’ +

‘{“UnitPrice”:2.5,”Quantity”:1.0,”ProductName”:”Ruler”},’ +

‘{“UnitPrice”:1.5,”Quantity”:2.0,”ProductName”:”Pen”}],”invoiceNumber”:2}’ +

‘]}’;

// Parse entire JSON response.

JSONParser parser = JSON.createParser(jsonStr);

while (parser.nextToken() != null) {

// Start at the array of invoices.

if (parser.getCurrentToken() == JSONToken.START_ARRAY) {

while (parser.nextToken() != null) {

// Advance to the start object marker to

//  find next invoice statement object.

if (parser.getCurrentToken() == JSONToken.START_OBJECT) {

// Read entire invoice object, including its array of line items.

Invoice inv = (Invoice)parser.readValueAs(Invoice.class);

system.debug(‘Invoice number: ‘ + inv.invoiceNumber);

system.debug(‘Size of list items: ‘ + inv.lineItems.size());

String s = JSON.serialize(inv);

system.debug(‘Serialized invoice: ‘ + s);

// Skip the child start array and start object markers.

parser.skipChildren();

}

}

}

}

}

// Inner classes used for serialization by readValuesAs().

public class Invoice {

public Double totalPrice;

public DateTime statementDate;

public Long invoiceNumber;

List<LineItem> lineItems;

public Invoice(Double price, DateTime dt, Long invNumber, List<LineItem> liList) {

totalPrice = price;

statementDate = dt;

invoiceNumber = invNumber;

lineItems = liList.clone();

}

}

public class LineItem {

public Double unitPrice;

public Double quantity;

public String productName;

}

Another way to do deserialization is as below.

Invoice inv = (Invoice)JSON.deserialize(jsonStr, Invoice.class);

This will convert a the response string into a single Invoice object. But what if we want to deserialise a list of Invoice object. In this case we will use the below code to deserialise the list

List<invoice> lstInvoice = (list<invoice>) JSON.deserialize(jsonStr list<invoice>.class);

This will parse the string into the respected object list we created in our apex class.

This approach seems easy but it is always better to use the JSONParser Class to serialize and deserialize the object/object list

Also, Have a look at the below resources:

  1. Best Salesforce Interview Questions book with Apex and Visualforce concept explained

Also, Have a look at the below learning resources:

  1. SOQL (Salesforce Object Query Language)

  2. Apex Trigger Best Practices and the Trigger Framework

  3. Salesforce Interview Question and Answers Part 2

  4. Salesforce Interview Questions on Test Class

  5. Salesforce-lightning-interview-questions-2018

     6. Salesforce Interview Questions Batch Class 

The post How to do JSON Parsing of a wrapper class in Salesforce appeared first on Salesforce Next Gen.

]]>
https://salesforcenextgen.com/how-to-do-json-parsing-of-a-wrapper-class-in-salesforce/feed/ 1
Salesforce Interview Questions on Test Class https://salesforcenextgen.com/salesforce-interview-questions-test-class/ https://salesforcenextgen.com/salesforce-interview-questions-test-class/#comments Thu, 20 Jul 2017 12:28:30 +0000 http://salesforcenextgen.com/?p=836 Salesforce Interview Questions on Test Class here you will find interview questions related to Apex Test Class, this will help you in acing the interview. What is test class and why it is necessary? A test class is a class which helps in checking the quality of code before it can be deployed to Salesforce …
Continue reading Salesforce Interview Questions on Test Class

The post Salesforce Interview Questions on Test Class appeared first on Salesforce Next Gen.

]]>
Salesforce Interview Questions on Test Class

here you will find interview questions related to Apex Test Class, this will help you in acing the interview.

What is test class and why it is necessary?

A test class is a class which helps in checking the quality of code before it can be deployed to Salesforce Production. It helps in code coverage of an Apex class or Trigger.

What is code coverage and what is the minimum code coverage for class and trigger?

Code Coverage is the percentage number of lines covered by the test class by a total number of lines need to be covered.

Minimum code coverage for the trigger is at least 1% and for class, the overall code coverage of production should be above 75% before a new component can be deployed to the production.

Does Salesforce count calls to system.debug() against the code coverage?

No, Salesforce does not count it against the code coverage.

Q How is a class defined as a test class ?

We use annotation isTest before a class to declare it as a test class. By declaring it with isTest Annotation it is not counted against the org’s limit of 3MB of Apex Code.

how is a test method defined?

A test method is defined as mentioned below:-

Syntax: static testMethod void testMethodName(){….. Your Code here ……..}

What is seeAllData and why it is recommended to avoid using it?

Test classes run in a different context, i.e. a test class have no idea about the data stored in Salesforce, by setting seeAllData=true => @isTest(seeAllData = true)

Enabling this attribute exposes the data from the database to the test class.

It is recommended not to use as the code coverage of you apex class or trigger will now be dependent on the data which is present in org and depending upon that the code coverage may change.

What is the role of Test.start() and Test.Stop()?

Test class also abide by the governor limit of Salesforce and we often find ourself hitting governor limits in the test class. To avoid hitting this scenario Salesforce provided us with Test.start() and test.stop().

  • Code written between these methods receives a fresh set of governor limits.
  • It runs asynchronous methods synchronously.
  • These can be used only once per testMethod.

What is System.runAs() Method used for in a test Class?

Default execution mode of a test class is system mode, and if we want to run this test class as a specific user then we use system.runAs().

How many types of Assert Statements are there and what is their purpose?

Assert statements are used to compare expected value with the actual value.

There are three types of assert statements :

  1. assertEquals(expVal, actVal); returns true if expVal Matches actVal.
  2. assertNotEqual(expVal, actVal); returns true if expVal does not match actVal.
  3. assertEquals(expVal > actVal); returns true if the condition is satisfied.

What is @testVisible used for while testing an Apex class?

There could be a possibility that we need to access a private class member, but due to its accessibility, it is not visible to test method. To make them visible to test method we use @Testvisible before any private member in Apex class.

What are the best practices for test class?

There are many considerations while writing a test class few are mentioned below:-

Code coverage should not depend on the existing data in the org, i.e. sellAllData should not be true

For testing trigger and batch class we should do bulk testing with at least 200 records.

Testing should be done for the entire scenario not only for the code coverage.

************** more questions to come

The post Salesforce Interview Questions on Test Class appeared first on Salesforce Next Gen.

]]>
https://salesforcenextgen.com/salesforce-interview-questions-test-class/feed/ 8