APEX

<<<<<<<Salesforce Apex Interview questions>>>>>>>>

1. What are the types of Collections available in Apex?

  1. List (ordered and allow duplicates)
  2. Set (unordered and won’t allow duplicates)
  3. Map (Key and value pair)

2. What is the difference between List and Set ?

List allows duplicates.Set doesn’t allow duplicates.
List is Ordered.
Set is unordered
We can access list elements with index.Set elements cannot be accessed with index.
We can sort list elements with sort method (default sorting order is ascending).sort method is not available for Set.
Contains method is not available in List.Contains method is available for Set to search for a particular element in the set.
We can process records which are stored in list using DML statements(insert, update, delete and undelete).We cannot process records which are stored in set using DML statements.

3. What are the map methods available in Apex?

//Map holds key and value pair.
   //Syntax: Map mapName = new Map();
   /*Map countryISTCodeMap = new Map();
   countryISTCodeMap.put('India','+91');
   countryISTCodeMap.put('USA','001');
   countryISTCodeMap.put('India','911');//replaces old value with new value.*/
   Map countryISTCodeMap = new Map{'India'=>'+91','USA'=>'345', 'India'=>'912'};
   
   system.debug('countryISTCodeMap result: '+countryISTCodeMap+' with size '+countryISTCodeMap.size());
   system.debug('countryISTCodeMap keys: '+countryISTCodeMap.keyset());
   system.debug('countryISTCodeMap values: '+countryISTCodeMap.values());
   system.debug('countryISTCodeMap search: '+countryISTCodeMap.containsKey('India'));
   system.debug('countryISTCodeMap fetching value based on key: '+countryISTCodeMap.get('India'));
   //map keys are case-sensitive.
   
  1. keyset(): To fetch only keys from the map.
  2. values(): To fetch only values from the map.
  3. containsKey(value): To search a key from the map.
  4. get(key): By supplying the key we can fetch the value.
  5. put(key,value): To add key and value in a map.

4. When should you build solutions declaratively(out of box) instead of with code?

As a salesforce best practice, if something can be done using Configurations (Declarative) then its preferred over coding. The declarative framework is optimized for the platform and is always preffered.

5. Explain how MVC architecture fit for Salesforce?

In salesforce, Apex Classes works as Controllers, Visualforce Pages works as View and Custom objects works as Model.

6. What is Trigger?

Trigger is a code that is executed before or after the record is updated or inserted.

7. When we Use a Before Trigger and After Trigger?

“Before” triggers to validate data or update fields on the same object.
“After” triggers to update parent or related records.

8. If salesforce allow use to update the same object or validate the same object using before and after both trigger event so why before trigger exist?

If any thing is possible in same object without Soql using before trigger event so why we go for a after trigger event.

9. What is the maximum batch size in a single trigger execution?

Default batch size is 200 ,However maximum batch size is 2000.

10. What are the trigger events?

Before Mode: Before the record is saving into the database, it will fire.

After Mode: After the record is saved into the database (doesn’t commit at this point of time), it will fire.

BeforeAfter
before insertafter insert
before updateafter update
before deleteafter delete
before Undelete event Not Availableafter undelete

11. What are the trigger context variables?

To capture the runtime information we use trigger context variables.
Below context variables will return either true or false.

  1. Trigger.isBefore (returns true if the trigger context is Before Mode)
  2. Trigger.isAfter (returns true if the trigger context is After Mode)
  3. Trigger.isInsert (returns true if the trigger context is Insert)
  4. Trigger.isUpdate (returns true if the trigger context is Update)
  5. Trigger.isDelete (returns true if the trigger context is Delete)
  6. Trigger.isUndelete (returns true if the trigger context is Undelete)
  7. Trigger.isExecuting (returns true if the apex class method is getting call from Apex Trigger)

Below context variables will store records at runtime.

  1. trigger.old (stores history (old versions) of the records.)
  2. trigger.oldMap (stores history (old versions) of the records along with id.)
  3. trigger.new (stores new version of the records.)
  4. trigger.newMap (stores new version of the records along with id.)

12. When to use before triggers and when to use after triggers?

Before Triggers

  1. To perform the validations we should use before triggers.
  2. If you are updating any field on the same object on which you are writing the trigger and no need to explicitly include the DML statemetns (already due to DML operation only trigger fire and it is still in progress at this point of time.)

After Triggers

  1. If you are dealing with relationship records and if you need record id in these situations we should use after trigger (in before insert record doesn’t contain the record id).

13. For the same event if there are multiple triggers on the object, how to control the order of execution?

We cannot control the order of execution in this situation. It is recommended to have only one trigger per one object.

Note: We can keep the logic of the apex trigger in an apex class and can invoke from that class.

14. What are the recursive triggers and how to avoid?

If we perform update operation on the record in after update event logic recursive triggers will arise.
Using static boolean variable in an apex class (we should not keep static boolean variable inside of the trigger) we can avoid recursive triggers.

15. What is MIXED-DML-OPERATION error and how to avoid?

If we perform DML operation on standard/custom object and global objects(User, UserRole, Group, GroupMember, Permission Set, etc…) in same transaction this error will come.

To avoid this error, we should perform DML operation on standard/custom object records in a different transaction.

In general all the apex classes and apex triggers execute synchronously (execute immediately).

if we perform DML operation on standard/custom object records asynchronously (execute in future context), we can avoid MIXED-DML-OPERATION error.

To execute logic asynchronously keep the logic in an apex method (in a separate apex class, not in same apex trigger) which is decorated with @future annotation.

Note: To analyse the code copy it and paste it in notepad for the convenience.
  public class TriggerUtility {
   /*
   1. Following future method execute asynchronously (whenever server is free it will execute in future context).
   2. We should not declare @future method in Apex Trigger.
   3. @future method should be always static.
   4. @future method accepts only primitive data types (Integer, String, Boolean, Date, etc...) as parameters and it won't accept 
   non-primitive data types (sObject,Custom Objects and standard Objects etc.. ) as parameters.
   5. @future method should not contain return type. Always it should be void.
   6. From an apex trigger we can make only make asynchronous call outs. To make call out we should include "callout = true" beside the future @annotation.
   7. We cannot perform synchronous call outs from Apex Trigger.
   */

   //Below is the example for the future method -
   @future(callout = true)
   public static void processAsync(primitive parameters) {
    //Logic to insert/update the standard/custom object.
   }
  }
   

16. What Is The Difference Between Trigger.new And Trigger.old?

Trigger.new:

Returns a list of the new versions of the sObject records
Note that this sObject list is only available in insert and update triggers
i.e., Trigger.new is available in before insert, after insert, before update and after update
In Trigger.new the records can only be modified in before triggers.

Trigger.old:

Returns a list of the old versions of the sObject records
Note that this sObject list is only available in update and delete triggers.
i.e., Trigger.old is available in after insert, after update, before delete and after update.

17. What is Apex Transaction in Salesforce?

An Apex transaction represents a set of operations that are executed as a single unit. The operations here include the DML operations which are responsible for querying records. All the DML operations in a transaction either complete successfully, or if an error occurs even in saving a single record, then the entire transaction is rolled back.

18. What is the order of execution in Salesforce?

1. Old record loaded from database (or initialized for new inserts)
2. New record values overwrite old values
3. System Validation Rules
4. All Apex “before” triggers
5. Custom Validation Rules
6. Record saved to database (but not committed)
7. Record reloaded from database
8. All Apex “after” triggers
9. Assignment rules
10.Auto-response rules
11.Workflow rules
12.Escalation rules
13.Parent Rollup Summary Formula value updated (if present)
14.Database commit
15.Post-commit logic (sending email)

19. What is the difference between trigger.new and trigger.newmap?

Trigger.new returns a list of the new versions of the sObject records.

Trigger.newMap returns a list of the new versions of the sObject records with the ids.

20. How to run trigger asynchronuosly?

If you use @future method trigger will run asynchronously.

21. What is the best practice of trigger?

1. One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2. Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your Org.

3. Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers

4. Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5. Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6. Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7. Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and query more

8. Use @future Appropriately
It is critical to writing your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9. Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

22. What is the difference between database.insert and insert?

Using insert if one record fails entire operation is stopped and none of the record is inserted into database, whereas with databse.insert partial insertion is supported.

23. Is it possible to call batch class from trigger.

Yes

24. What is the condition to call a method from trigger which is making callout?

The callout should be asynchronous.

25. What will you do if a method inside apex class need to be executed only when it is getting called from trigger?

We will use trigger.isexecuting in apex class to check if the method inside apex class is getting called from trigger and will execute the method if getting called from trigger.

26. There is a validation rule which will fire if amount = 100 and will display the error message. There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000. what will the value of the amount field.

Validation rules will fire first then workflow rules will fire. So, the answer is 100 (Even though there is a validation rule because of the workflow rule it will accept 100 in the amount field).

27. There is a before trigger which will fire if amount = 100 and will display the error message. There is a workflow rule which will fire if amount > 100 and will update amount field to 100. One of user saved the record by giving value as 1000. what will the value of the amount field.

It will throw the validation error because after the workflow field update before triggers fire one more time.

28. What is Object?

An instance of a class is called Object. An instance is a specific object built from a specific class. It is assigned to a reference variable that is used to access all of the instance’s properties and methods. When you make a new instance the process is called instantiation and is typically done using the new keyword.

29. What is SObject?

SObjects are the objects of Salesforce in which you store the data. For example, Account, Contact, etc., are custom objects. You can create object instances of these sObjects.

30. What is SOQL?

This is Salesforce Object Query Language designed to work with SFDC Database. It can search a record on a given criterion only in single sObject.

Like SOSL, it cannot search across multiple objects but it does support nested queries.

When SOQL is embedded in apex , it is referred to as inline SOQL.

31. What is SOSL?

Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has the capability of searching a particular string across multiple objects.

SOSL statements evaluate to a list of sObjects, wherein, each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query.

Ex:- FIND {Test} IN ALL FIELDS RETURNING Account(Name), Contact(FirstName,LastName)

32. Differences of SOQL and SOSL?

SOQL(Salesforce Object Query Language)SOSL(Salesforce Object Search Language)
Only one object at a time can be searched(Search in Single object)Many object can be searched at a time(Search in entire organization or Database)
Query all type of fieldQuery on only email, text or phone
It can be used in classes n triggersIt can use in classes but not in trigger
DML Operation can be performed on query resultsDML Operation cannot be performed on search results
Return RecordsReturn Field

33. How Many Ways We Can Invoke The Apex Class?

1. Visualforce page
2. Trigger
3. Web Services
4. Email Services
5. Process Builder

34. What is the difference between with sharing and without sharing?

With Sharing:

If you declare a class as a With Sharing, sharing rules given to the current user will be taken into consideration and the user can access and perform the operations based on the permissions given to him on objects and fields. (field level security, sharing rules)


public with sharing class sharingClass {

// Code here

}

Without Sharing:

If you declare a class as a Without Sharing then this apex class runs in system mode which means apex code has access to all the objects and fields irrespective of current users sharing rules, fields level security, object permissions.

  • Note: If the class is not declared as With Sharing or Without Sharing then the class is by default taken as Without Sharing.
  • Both inner class and outer classes can be declared as With Sharing.
  • If inner class is declared as With Sharing and top-level class is declared as without sharing, then the entire context will run in With Sharing context.
  • Outer class is declared as With Sharing and inner class is declared as Without Sharing then inner class runs in Without Sharing context only. (Inner classes don’t take the sharing properties from outer class).
public without sharing class noSharing {

// Code here

}

35. What are setter and getter methods?

Getter and Setter methods in salesforce are used to pass data from controller to visualforce and vice versa.

setter method value will be passed from visualforce page to controller ( Apex class) and same can be retrieved back to visualforce page through controller getter method.

36. Explain Difference In Count() And Count(fieldname) In Soql.?

COUNT()

COUNT() must be the only element in the SELECT list.
You can use COUNT() with a LIMIT clause.
You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.
You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.

COUNT(fieldName)

You can use COUNT(fieldName) with an ORDER BY clause.
You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.

37. Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities?

We will need “ALL Rows” clause of SOQL.
SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS

38. How can you lock record using SOQL so it cannot be modified by other user?

we will need “FOR UPDATE” clause of SOQL.
Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

38. Difference between insert/update and Database.insert/ Database.update?

insert/update
Assume that you are inserting 100 records. If any one of the record fail due to error then entire operation will fail. None of the records will be saved into the database.

Database.insert/Database.update
Assume that you are inserting 100 records. If any one of the record fail due to error then it will perform partial operation (valid records will be inserted/updated) if we use Database.insert(list,false)/ Database.update(list,false).

39. What are the aggregate functions supported by salesforce SOQL?

Following aggregate functions are supported by salesforce SOQL
1. SUM()
2. MIN()
3. MAX()
4. COUNT()
5. AVG()
6. COUNT_DISTINCT()

40. There is a Queue with name MyQueue. How to query it using SOQL query from the database?

Queues will store in Group object. To query for MyQueue from the database using SOQL, we should use the following syntax –

  Group grp = [select Id, Name from Group where Name = 'MyQueue' and Type = 'Queue' Limit 1];

41. Governor Limits for DML statements ?

  1. Number of DML statements per transaction: 150 (as a whole including insert, update, delete and undelete)
  2. Number of rows processed per DML stmt: 10000

42. Write a sample aggregate query or explain how to write a aggregate queries?

The return types of Aggregate functions are always an array of AggregateResult.

AggregateResult[] ar = [select AVG(Amount) aver from Opportunity];
Object avgAmt = ar[0].get(‘aver’);

43. Governor limits in salesforce.com?

  1. Total number of SOQL queries issued: 100
  2. Total number of records retrieved by SOQL queries; 50,000
  3. Total number of records retrieved by Database.getQueryLocator: 10,000
  4. Total number of SOSL queries issued: 20
  5. Total number of records retrieved by a single SOSL query: 2,000
  6. Total number of DML statements issued: 150
  7. Total number of records processed as a result of DML statements, Approval.process, or database.emptyRecycleBin: 10,000
  8. Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, or delete statements: 16
  9. Total number of callouts (HTTP requests or Web services calls) in a transaction: 100
  10. Maximum cumulative timeout for all callouts (HTTP requests or Web services calls) in a transaction: 120 seconds
  11. Maximum number of methods with the future annotation allowed per Apex invocation: 50
  12. Maximum number of Apex jobs added to the queue with System.enqueueJob: 50
  13. Total number of sendEmail methods allowed: 10
  14. Total heap size: 6 MB
  15. Maximum CPU time on the Salesforce servers: 10,000 milliseconds
  16. Maximum execution time for each Apex transaction: 10 minutes
  17. Maximum number of push notification method calls allowed per Apex transaction: 10
  18. Maximum number of push notifications that can be sent in each push notification method call: 2,000

44. Can we create 2 opportunities while the Lead conversion ?

Yes using Apex code.

45. How to get Custom setting with out SOQL and SOSL?

For example:If there is custom setting of name ISO_Country,

SO_Country__c code = ISO_Country__c.getInstance(‘USA’);

//To return a map of data sets defined for the custom object (all records in the custom object), //you would use:

Map mapCodes = ISO_Country__c.getAll();

// display the ISO code for USA

System.debug(‘ISO Code: ‘+mapCodes.get(‘USA’).ISO_Code__c);

//Alternatively you can return the map as a list:

List listCodes = ISO_Country__c.getAll().values();

46.  How to get all the fields of Sobject using dynamic apex?

Map m = Schema.getGlobalDescribe() ;

Schema.SObjectType s = m.get('API_Name_Of_SObject') ;

Schema.DescribeSObjectResult r = s.getDescribe() ;

Map fields = r.fields.getMap();

47. Why Apex is quite different from another lenguage?

Apex runs in a multi-tenant environment and is very controlled in its invocation and governor limits.
• To avoid confusion with case-insensitive SOQL queries, Apex is also case-insensitive.
• Apex is on-demand and is compiled and executed in cloud.
• Apex is not a general purpose programming language, but is instead a proprietary language used for specific business logic functions.
• Apex requires unit testing for development into a production environment.

47. When we have to write Apex in Salesforce?

  • To create web services that integrate Salesforce with other applications.
  • To implement custom validation on sObjects.
  • To execute custom apex logic when a DML operation is performed.
  • To implement functionality that can’t be implemented using existing workflows flows and process builder’s functionality.
  • To setup email services, you need to include processing the contents, headers, and attachments of email using apex code.

48. What is Difference between break and Continue?

break:- break keyword is used to exit the enclosing loop prematurely.

for (Integer i = 0; i < 10; i++) {

if( I == 1){

     break;

}

System.debug(i+1);

}

Output:- 1

continue:- continue keyword skips to the next iteration of the loop.

for (Integer i = 0; i < 10; i++) {

if( i == 1){

     Continue;

}
System.debug(i+1);

}

Output:- 1,3,4,5,6,7,8,9,10

49. What is Static & Non-Static Variables and its Differences?

AccessA static variable can be accessed by static members as well as non-static member functions.A non-static variable can not be accessed by static member functions.
SharingA static variable acts as a global variable and is shared among all the objects of the class.A non-static variables are specific to instance object in which they are created.
Memory allocationStatic variables occupies less space and memory allocation happens once.A non-static variable may occupy more space. Memory allocation may happen at run time.
KeywordA static variable is declared using static keyword.A normal variable is not required to have any special keyword.

50. What is Access Modifier and what are those?

PrivateThis keyword can only be used with inner classes. The private access modifier declares that this class is only known locally, that is, only by this section of code.
PublicThe public access modifier declares that this class is visible in your application or namespace.
GlobalThe global access modifier declares that this class is known by all Apex code everywhere.
With Sharing / Without SharingThe with sharing and without sharing keywords specify the sharing mode for this class. The with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class
VirtualThe virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual.
AbstractThe abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.

51. What is Constructors in Salesforce?

A constructor is a code that is invoked when an object is created from the class blueprint. It has the same name as the class name. constructor will have same name as class name and does not have return types.

52. What Are Global Variables Explain With Examples?

Global variables must be referenced using Visualforce expression syntax to be evaluated, for example, {!$User.Name}.

List of available global variables are as below:

1. $Action
2. $Api
3. $Component
4. $ComponentLabel
5. $CurrentPage
6. $Label
7. $Label.Site
8. $ObjectType
9. $Organization
10. $Page
11. $Profile
12. $Resource
13. $SControl
14. $Setup
15. $Site
16. $User
17. $UserRole
18. $System.OriginDateTime
19. $ User.UITheme and $User.UIThemeDisplayed

53. What is Wrapper Class?

A Wrapper class is a class whose instances are collection of other objects.

It is used to display different objects on a Visual Force page in same table.

54. What is difference between public and global class in Apex ?

Public class can be accessed within application or namespace. This is not exactly like public modifier in Java.

Global class visible everywhere, any application or namespace. WebService must be declared as Global and which can be accessed inside Javascript also. It is like public modifier in Java.

55. What are the effects of using the transient keyword?

The transient key word prevents the data from being saved into the view state. This should be used for very temporary variables.

55. Where we can use workflow rather than trigger?

If any thing we need to perform in same object we should go for a workflow rule and in case of master detail relationship we also update child to parent.

56. Explain Considerations for Static keyword in Apex?

Apex classes cannot be static.
Static allowed only in outer class.
Static variables not transferred as a part of View State.
Static variables and static block runs in order in which they are written in class.
Static variables are static only in scope of request.

57. What is the use of save point in java script?

This will use for the rollback changes.

58. How many types of email services in salesforce? Write a apex code to send a email?

Their are two types of email services in salesforce

1. Inbound Email Services.
2. Outbound Email Services.

Sample code snippet to send an email using apex code

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{‘talk2srikrishna@gmail.com’};
mail.setToAddress(toAddresses);
mail.setSubject(‘Sample Mail Subject’);
mail.setPlainTextBody(‘Hello World!’);
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});

59. How can we hard delete a record using a Apex class/by code?

ALL ROWS keyword can be used to get all the records including records in the recycle bin.
Below is the sample code to delete contact records from recycle bin

List dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS];
Database.emptyRecycleBin( dContactList );

60. What is the purpose of writing the test class?

After developing an apex class or apex trigger we should write the unit tests and ensure that we are able to execute at least 75% of the lines of code.

If you are moving the code from sandbox to sandbox regarding code coverage you won’t face any issue.

If you are moving the code from sandbox to production, you need to include all the test classes at the time of deployment and salesforce will run all the test classes which you included for the deployment as well as test classes which are already present in production, if the code coverage is less than 75% deployment will fail.

61.  Syntax of testMethod?

@isTest
private class MyTestClass {

static testMethod void myTest1() {
}

static testMethod void myTest2() {
}

}

62. What is the purpose of seeAllData?

if we mention @isTest(seeAllData = true) then test class can recognize the existing data in the database

See the below examples –

From a List Custom Settings we cannot fetch the existing data without seeAllData = true in test class.
Suppose you have a custom object called ‘CustomObject__c’ and it contains many records, we cannot fetch the existing data without seeAllData = true in test class.
Note: It is not recommended to use seeAllData = true for a test class. Based on the existing data in database code coverage will impact.

63. What is the purpose of Test.startTest() and Test.stopTest()?

Test.startTest() and Test.stopTest() maintains fresh set of governor limits. Assume that you are consuming 99 SOQL queries outside of Test.startTest() and Test.stopTest() then if you include any SOQL inside of Test.startTest() and Test.stopTest() count will start from 1.

Per testMethod we can use Test.startTest() and Test.stopTest() only for one time.

To execute asynchronous methods synchronously we can call those methods from inside of Test.startTest() and Test.stopTest().

64. What is the purpose of system.runAs()?

By default test class runs in System Mode. If you want to execute a piece of code in a certain user context then we can use system.runAs(UserInstance).

To avoid MIXED-DML-OPERATION error we can include DML statements inside of system.runAs(), still the error persists keep DML statements inside of Test.startTest() and Test.stopTest().

65. What is the purpose of Test.isRunningTest()?

Sometimes we cannot satisfy certain if conditions for the apex classes, in those situations on those if conditions we can add Test.isRunningTest separated with or condition.
Example: if(condition || Test.isRunningTest())

66. What are the assert statements?

To compare Actual value and Expected value we use assert statements.

Types of assert statements

system.assertEquals(val1,val2): If both val1 and val2 are same then test class run successfully otherwise test class will fail.
system.assertNotEquals(val1,val2): If both val1 and val2 are not same then test class run successfully otherwise test class will fail.
system.assertEquals(val1> val2): If the condition satisfied then test class run successfully otherwise test class will fail.

67. What is the test class best practice?

1. Test class must start with @isTest annotation.
2. Test environment support @testVisible, @testSetUp as well.
3. Unit test is to test particular piece of code working properly or not.
4. Unit test method takes no argument, commit no data to database, send no email, flagged with testMethod keyword.
5. To deploy to production at-least 75% code coverage is required.
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit.
9. We should not focus on the percentage of code coverage, we should make sure that every use case should be covered including positive, negative, bulk and single record.
Single Action –To verify that the single record produces the correct an expected result.
Bulk action –Any apex record trigger, class or extension must be invoked for 1-200 records.
Positive behavior– Test every expected behavior occurs through every expected permutation, I,e user filled out every correct data and not go past the limit.
Negative Testcase – Not to add future date, Not to specify the negative amount.
Restricted User -Test whether a user with restricted access used in your code.
10. Test class should be annotated with @isTest.
11 . @isTest annotation with test method is equivalent to testMethod keyword.
12. Test method should static and no void return type.
13. Test class and method default access is private , no matter to add access specifier.
14. classes with @isTest annotation can’t be an interface or enum.
15. Test method code can’t be invoked by non-test request.
16. @Testvisible annotation to make visible private methods inside test classes.
17. The test method cannot be used to test web-service call out. Please use callout mock.
18. You can’t send email from test method.
19.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true).
20. Accessing static resource test records in test class e,g List accList=Test.loadData(Account,SobjectType,resource name’).
21. Create TestFactory class with @isTest annotation to exclude from organization code size limit.
22. @testSetup to create test records once in a method and use in every test method in the test class.
23.  As apex runs in system mode so the permission and record sharing is not taken into account. So we need to use a system.runAs to enforce record sharing.
24. System.runAs will not enforce user permission or field level permission.
25. Every test to runAs count against the total number of DML issued in the process

68. What is Batch Apex?

Batch Apex is used to run large jobs (think thousands or millions of records!) that would exceed normal processing limits. Using Batch Apex, you can process records asynchronously in batches (hence the name, “Batch Apex”) to stay within platform limits. If you have a lot of records to process, for example, data cleansing or archiving, Batch Apex is probably your best solution.

  • With Batch Apex we can process maximum of 50 million records.
  • Batch Apex is asynchronous (execute in future context).
  • While writing the batch class we should inherit Database.Batchable interface.
  • Database is a built in global class which contains inner global interface.

This functionality has two awesome advantages:

  • Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits.
  • If one batch fails to process successfully, all other successful batch transactions aren’t rolled back.

69. Write a syntax and structure of batch class?

global class MyBatchClass implements Database.Batchable {

global (Database.QueryLocator | Iterable) start(Database.BatchableContext bc) {
// collect the batches of records or objects to be passed to execute
}

global void execute(Database.BatchableContext bc, List
records){
// process each batch of records
}

global void finish(Database.BatchableContext bc){
// execute any post-processing operations
}

}

Execute in developer console:-

BatchDemo bd = new BatchDemo();
database.executebatch(bd);

70. What are the Batch Apex methods?

Since we are inheriting Database.Batchable interface we should implement all the method prototypes declared in the interface.

We should implement the following global methods –

  1. start: It will prepare the records to process and execute only one time.
  2. execute: It will take the records prepared in start method and split those records into batches and it will execute multiple times. For example if the start method is returning 1000 records then execute method executes 5 times if you don’t mention the batch size (Default Batch Size is: 200). Maximum batch size is: 2000.
  3. finish: We can perform post commit logic like sending emails with the success or error information. It will execute only one time.

71. Suppose we have a batch size of 10 and we have 50 records so how many times each methods calls in batch class ?

Start method call at once.
Execute method call at five time.
Finish method call at once

72. How to schedule batch apex?

To schedule the batch class we should write a separate class by implementing Schedulable interface.

After writing the above mentioned class to schedule navigate to: Develop> Apex Classes> Schedule Apex.

By clicking on Schedule Apex button we can schedule the batch class through user interface.

Note: Through user interface we cannot schedule in hours/minutes.

Schedulable Class Syntax:

global class SchedulableUsage implements Schedulable {
   global void execute(SchedulableContext sc) {
    BatchUsage bu = new BatchUsage();
    //Database.executeBatch(bu);//Default Batch Size is: 200.
    Database.executeBatch(bu,1500);//Max. Batch Size is: 2000.
   }
  }

73. How to schedule batch apex in minutes/hours?

To schedule the batch class in minutes/hours, in the finish method we should use System.schedule method which will take 3 parameters Job Name, Chrone Expression and schedulable class instance name respectively.

  /*** Scheduling in minutes or hours ***/
  //Create object for schedulable class
  SchedulableUsage su = new SchedulableUsage();
  //Preparing chron_exp
  Datetime sysTime = System.now();
  sysTime = sysTime.addminutes(6);
  String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' +
  sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();            
  System.schedule('Dep Update'+sysTime.getTime(),chron_exp, su);

74. Is it possible to call future method from a batch class?

We cannot call one asynchronous process from another asynchronous process.

Since @future method and Batch Class both are asynchronous we cannot call a future method from the batch class or we cannot call a batch class from the future method.

75. How many batch jobs can be active/queued at a time?

Up to 5 batch jobs can be queued or active.

76.  Is it possbile to write batch class and schedulable class in a same class?

By implementing Database.Batchable and Schedulable interfaces we can implement the methods in a same class.

77. How to maintain the state between the methods of batch class?

By default batch class is stateless (variable value which is stored in one method cannot be remembered in another method).

To maintain the state for the batch class, we should inherit Database.Stateful interface.

Scenario: In a set list of emails are stored in execute method. In the finish method that set is not having any emails. What is the reason?

Answer: By default batch class is stateless. Emails which are added to set can be remembered only in execute method. If we try to access the set in finish method you won’t see those emails. In finish method if you want to access those emails of that set we should inherit the interface called Database.Stateful.

78. Is it possible to call batch class from one more batch class?

Yes it is possible

79. Is it possible to call future method from a batch class?

We cannot call one asynchronous process from another asynchronous process.

Since @future method and Batch Class both are asynchronous we cannot call future method from batch class or we cannot call batch class from the future method.

80. How to cover the code for a batch class?

To cover the code for the batch class we should call the batch class from the inside of the Test.startTest() and Test.stopTest().

    Test.startTest();
  //Call the batch class from here.
    Test.stopTest();

81. Is it possible to call batch class from trigger?

Yes it is possible, we can call a batch apex from trigger but we should always keep in mind that we should not call batch apex from trigger each time as this will exceeds the governor limit this is because of the reason that we can only have 5 apex jobs queued or executing at a time.

82. What is Future method?

Future method is used to run processes in a separate thread, at a later time when system resources become available.

83. What is future method syntax? And some use cases of future methods?

global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}

Callouts to external Web services. If you are making callouts from a trigger or after performing a DML operation, you must use a future or queueable method. A callout in a trigger would hold the database connection open for the lifetime of the callout and that is a “no-no” in a multi-tenant environment.
Operations you want to run in their own thread when time permits such as some sort of resource-intensive calculation or processing of records.
Isolating DML operations on different sObject types to prevent the mixed DML error. This is somewhat of an edge-case but you may occasionally run across this issue. See sObjects That Cannot Be Used Together in DML Operations for more details.

84. Few considerations for @Future annotation in Apex?

  • Method must be static
  • Cannot return anything ( Only Void )
  • To test @future methods, you should use startTest and stopTest to make it synchronous inside Test class.
  • Parameter to @future method can only be primitive or collection of primitive data type.
  • Cannot be used inside VF in Constructor, Set or Get methods.
  • @future method cannot call other @future method.

85. Why we cannot pass objects as arguments in future method?

Object data might change between the time you call the future method and the time it actually executes.So,we pass record id.

86. IF downtime occurs and future method was running what will happen?

The Future method execution will be rolled back and will restart after downtime overs.

87. IF the future method was queued before a service maintenance what will happen?

It will remains in queue and when maintenance is over and resources are available it will get execute.

88. In an apex invocation how many methods that we can write as future annotations?

10

89. What is Queueable Class?

Queueable Apex allows you to submit jobs for asynchronous processing similar to future methods with the following additional benefits:

  • Non-primitive types: Your Queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
  • Monitoring: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
  • Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some sequential processing.

90. Queueale Class code structure?

public class SomeClass implements Queueable {
    public void execute(QueueableContext context) {
        // awesome code here
    }
}

91. Queueable scanarion with Example

A common scenario is to take some set of sObject records, execute some processing such as making a callout to an external REST endpoint or perform some calculations and then update them in the database asynchronously. Since @future methods are limited to primitive data types (or arrays or collections of primitives), queueable Apex is an ideal choice. The following code takes a collection of Account records, sets the parentId for each record, and then updates the records in the database.

public class UpdateParentAccount implements Queueable {
    private List<Account> accounts;
    private ID parent;
    public UpdateParentAccount(List<Account> records, ID id) {
        this.accounts = records;
        this.parent = id;
    }
    public void execute(QueueableContext context) {
        for (Account account : accounts) {
          account.parentId = parent;
          // perform other processing or callout
        }
        update accounts;
    }
}

To add this class as a job on the queue, execute the following code:

// find all accounts in ‘NY’
List<Account> accounts = [select id from account where billingstate = ‘NY’];
// find a specific parent account for all records
Id parentId = [select id from account where name = 'ACME Corp'][0].Id;
// instantiate a new instance of the Queueable class
UpdateParentAccount updateJob = new UpdateParentAccount(accounts, parentId);
// enqueue the job for processing
ID jobID = System.enqueueJob(updateJob);

After you submit your queueable class for execution, the job is added to the queue and will be processed when system resources become available.

You can use the new job ID to monitor progress, either through the Apex Jobs page or programmatically by querying AsyncApexJob:

SELECT Id, Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :jobID

92. How to write a queueable test class?

The following code sample shows how to test the execution of a queueable job in a test method. It looks very similar to Batch Apex testing. To ensure that the queueable process runs within the test method, the job is submitted to the queue between the Test.startTest and Test.stopTest block. The system executes all asynchronous processes started in a test method synchronously after the Test.stopTest statement. Next, the test method verifies the results of the queueable job by querying the account records that the job updated.

@isTest
public class UpdateParentAccountTest {
    @testSetup
    static void setup() {
        List<Account> accounts = new List<Account>();
        // add a parent account
        accounts.add(new Account(name='Parent'));
        // add 100 child accounts
        for (Integer i = 0; i < 100; i++) {
            accounts.add(new Account(
                name='Test Account'+i
            ));
        }
        insert accounts;
    }
    static testmethod void testQueueable() {
        // query for test data to pass to queueable class
        Id parentId = [select id from account where name = 'Parent'][0].Id;
        List<Account> accounts = [select id, name from account where name like 'Test Account%'];
        // Create our Queueable instance
        UpdateParentAccount updater = new UpdateParentAccount(accounts, parentId);
        // startTest/stopTest block to force async processes to run
        Test.startTest();
        System.enqueueJob(updater);
        Test.stopTest();
        // Validate the job ran. Check if record have correct parentId now
        System.assertEquals(100, [select count() from account where parentId = :parentId]);
    }
}

93. If the batch is executed without the optional scope parameter and If in batch apex suppose we have 600 jobs and there are total 200 records to be proceeds in each transaction,so in total we have 3 transaction.If first transaction succeeds but second fails so in this case the records update done in first transaction are rolled back or not?

It will not be rolled back.

94. When to use Database.Stateful   in batch apex?

If we implements Database.Stateful we can maintained state across transactions.
Only instance variable hold values static members does not hold values.

suppose we have 600 jobs and there are total 200 records to be proceeds in each transaction,so if we want to count records as batch proceeds maintaining state is important as after 200 set of records new transaction will start and members will loose their values. By implementing 
Database.Stateful we can maintain state after transaction is over and can store previous values.

global class myClass implements Database.Batchable<sObject>, Database.Stateful{

}

95. What are the parameters in system.schedule(Parameters) represents?

system.schedule(‘jobName ‘, expression, instance of schedulable class);

96. With the before Insert event which context variable is correct Trigger.new or Trigger.newmap?

As the event is before insert only trigger.new will be supported.

Trigger.newmap will not be supported as we do not have id of record before the record is inserted.

100. What will you do if a method inside apex class need to be executed only when it is getting called from trigger?

We will use trigger.isexecuting in apex class to check if the method inside apex class is getting called from trigger and will execute the method if getting called from trigger.

101. What will happen if you forgot to store remote site url in remote site setting?

The callout  to external system will fail.

102. How to query object having more than 50,000 records?

The total number of records that can be queried by soql queries is 50,000 record. If we query more than 50,000 record we exceeds the heap limit.

To avoid this we should use SOQL query for loop it can process multiple batches of record using call to query and query more.

for (List<Account> acct : [SELECT id, name FROM account

                            WHERE name LIKE ‘Test’]) {

    // Your logic here

}

//A runtime exception is thrown if the below query returns enough records to exceed your heap limit.

Account[] accts = [SELECT id FROM account];

103. Is it possible to call a batch class  from trigger and is it possible to make a call to apex callout method from trigger?

Yes it is possible to call a batch class from trigger but in case of call to apex callout method the method needs to be asynchronous.

104. What will happen if a class is not declared with “With sharing” or “Without sharing” and it get called from another class which is declared with “With sharing”?

If we do not declare class with “With sharing” or “Without sharing”  the class will not take into account the sharing rules but if this class is called from another class which is declared with “With sharing” it will take into account the sharing rules.

105. IF the class with “With sharing” is calling method of another class with “Without sharing” what will happen?

IF the class with “With sharing” is calling method of another class with “Without sharing” than the method inside “Without sharing” class will execute without sharing rules.

106. IF the class with “Without sharing” is calling method of another class with “With sharing” what will happen?

IF the class with “Without sharing” is calling method of another class with “With sharing” than the method inside “With sharing” class will execute with sharing rules.

106. Let say user do not have permission on a child object and he is having permission on parent object to read/create/edit/delete parent object, If I create a trigger on parent object to insert a child record after parent record is created, will it create a child record or not after user insert parent record manually?

It will create a child record (Trigger/apex class runs in system mode).

107. If in the above case from trigger I am calling apex class which is in “with sharing” mode and where I am inserting child record after parent is inserted manually by user so will it create a child record?

It will create a child record.(With sharing keyword has nothing to do with user permissions it only takes into account the sharing rules for the user.).