Apex Testing, Debugging, Deployment Flashcards

1
Q

Apex testing coverage

A

Cover as many lines of code as possible. Before you can deploy Apex or package it for AppExchange, the following must be true.

  • Unit tests must cover at least 75% of your Apex code, and all of those tests must complete successfully.
  • Every trigger must have some test coverage.
  • All classes and triggers must compile successfully.
  • When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
  • Calls to System.debug aren’t counted as part of Apex code coverage.
  • Test methods and test classes aren’t counted as part of Apex code coverage.
  • While only 75% of your Apex code must be covered by tests, don’t focus on the percentage of code that is covered. Instead, make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This approach ensures that 75% or more of your code is covered by unit tests.
    Tests don’t run in parallel in metadata deployments, package installations, or change set deployments.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What to Test in Apex

A

Single action
Bulk actions
Positive behavior
Negative behavior
Restricted user

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What Are Apex Unit Tests?

A

Unit test methods take no arguments, commit no data to the database, and send no emails. Such methods are flagged with the @IsTest annotation in the method definition. Unit test methods must be defined in test classes, that is, classes annotated with @IsTest.
The @IsTest annotation on methods is equivalent to the testMethod keyword. As best practice, Salesforce recommends that you use @IsTest rather than testMethod. The testMethod keyword may be versioned out in a future release.
Classes and methods defined as @IsTest can be either private or public. The access level of test classes methods doesn’t matter. You need not add an access modifier when defining a test class or test methods. The default access level in Apex is private. The testing framework can always find the test methods and execute them, regardless of their access level.
Classes defined as @IsTest must be top-level classes and can’t be interfaces or enums.
Methods of a test class can only be called from a test method or code invoked by a test method; non-test requests can’t invoke it.

Unit Test Considerations
Here are some things to note about unit tests.

  • Starting with Salesforce API 28.0, test methods can no longer reside in non-test classes and must be part of classes annotated with IsTest.
  • Test methods can’t be used to test Web service callouts. Instead, use mock callouts.
  • You can’t send email messages from a test method.
  • Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.
  • If the value of a static member variable in a test class is changed in a testSetup or test method, the new value isn’t preserved. Other test methods in this class get the original value of the static member variable. This behavior also applies when the static member variable is defined in another class and accessed in test methods.
  • Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren’t available when test methods modify the associated record.
  • Since test methods don’t commit data, they don’t result in the creation of FeedTrackedChange records. Similarly, field history tracking records can’t be created in test methods because they require other sObject records to be committed first. For example, AccountHistory records can’t be created in test methods because Account records must be committed first.
  • If your tests include DML, make sure that you don’t exceed the MAX_DML_ROWS limit.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Accessing Private Test Class Members

A

Test methods are defined in a test class, separate from the class they test. This can present a problem when having to access a private class member variable from the test method, or when calling a private method. Because these are private, they aren’t visible to the test class. You can either modify the code in your class to expose public methods that will make use of these private class members, or you can simply annotate these private class members with TestVisible. When you annotate private or protected members with this annotation, they can be accessed by test methods and only code running in test context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Understanding Test Data

A

Apex test data is transient and isn’t committed to the database.
This means that after a test method finishes execution, the data inserted by the test doesn’t persist in the database. As a result, there is no need to delete any test data at the conclusion of a test. Likewise, all the changes to existing records, such as updates or deletions, don’t persist. This transient behavior of test data makes the management of data easier as you don’t have to perform any test data cleanup. At the same time, if your tests access organization data, this prevents accidental deletions or modifications to existing records.

By default, existing organization data isn’t visible to test methods, with the exception of certain setup objects. You should create test data for your test methods whenever possible. However, test code saved against Salesforce API version 23.0 or earlier has access to all data in the organization.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Isolation of Test Data from Organization Data in Unit Tests

A

By default, Apex test methods (API version 24.0 and later) can’t access pre-existing org data such as standard objects, custom objects, and custom settings data. They can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests. These are some examples of such objects.
User
Profile
Organization
CronTrigger
RecordType
ApexClass
ApexTrigger
ApexComponent
ApexPage
Whenever possible, create test data for each test. You can disable this restriction by annotating your test class or test method with the IsTest(SeeAllData=true) annotation.

Test code saved using Salesforce API version 23.0 or earlier continues to have access to all data in the organization and its data access is unchanged.

Data Access Considerations
When working with data silo Apex tests(A data silo test is a test method that doesn’t have access to org data.), cross-object field references using the Owner relationship aren’t supported. Due to this limitation, SELECT Owner.IsActive FROM Account returns null when run within a data silo Apex test.
If a new test method saved using Salesforce API version 24.0 or later calls a method in another class saved using version 23.0 or earlier, the data access restrictions of the caller are enforced in the called method. The called method can’t access organization data because the caller can’t access it, even though it was saved in an earlier version.
The IsTest(SeeAllData=true) annotation has no effect when added to Apex code saved using Salesforce API version 23.0 and earlier.
This access restriction to test data applies to all code running in test context. For example, if a test method causes a trigger to execute and the test can’t access organization data, the trigger won’t be able to either.
If a test makes a Visualforce request, the executing test stays in test context but runs in a different thread. Therefore, test data isolation is no longer enforced. In this case, the test will be able to access all data in the organization after initiating the Visualforce request. However, if the Visualforce request performs a callback, such as a JavaScript remoting call, any data inserted by the callback isn’t visible to the test.
The VLOOKUP validation rule function, in API version 27.0 and earlier, always looks up org data in addition to test data when fired by a running Apex test. Starting with version 28.0, the VLOOKUP validation rule function no longer accesses organization data from a running Apex test. The function looks up only data created by the test, unless the test class or method is annotated with IsTest(SeeAllData=true).
There can be some cases where you can’t create certain types of data from your test method because of specific limitations. Here are some examples of such limitations.
Some standard objects aren’t creatable.
For some sObjects that have fields with unique constraints, inserting duplicate sObject records results in an error. For example, inserting CollaborationGroup sObjects with the same names results in an error because CollaborationGroup records must have unique names. This error occurs whether your test is annotated with IsTest(SeeAllData=true), or not.
Records that are created only after related records are committed to the database, like tracked changes in Chatter. Tracked changes for a record (FeedTrackedChange records) in Chatter feeds aren’t available when test methods modify the associated record. FeedTrackedChange records require the change to the parent record they’re associated with to be committed to the database before they’re created. Since test methods don’t commit data, they don’t result in the creation of FeedTrackedChange records. Similarly, field history tracking records can’t be created in test methods because they require other sObject records to be committed first. For example, AccountHistory records can’t be created in test methods because Account records must be committed first.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Using the isTest(SeeAllData=True) Annotation

A

Annotate your test class or test method with IsTest(SeeAllData=true) to open up data access to records in your organization. The IsTest(SeeAllData=true) annotation applies to data queries but doesn’t apply to record creation or changes, including deletions. New and changed records are still rolled back in Apex tests even when using the annotation.
Warning:
By annotating your class with @isTest(SeeAllData=true), you allow test methods to access all org records. The best practice, however, is to run Apex tests with data silo using @isTest(SeeAllData=false). Depending on the API version you’re using, the default annotation can vary.
Considerations for the @IsTest(SeeAllData=true) Annotation
If a test class is defined with the @IsTest(SeeAllData=true) annotation, the SeeAllData=true applies to all test methods that don’t explicitly set the SeeAllData keyword.
The @IsTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level. However, if the containing class has been annotated with @IsTest(SeeAllData=true), annotating a method with @IsTest(SeeAllData=false) is ignored for that method. In this case, that method still has access to all the data in the organization. Annotating a method with @IsTest(SeeAllData=true) overrides, for that method, an @IsTest(SeeAllData=false) annotation on the class.
@IsTest(SeeAllData=true) and @IsTest(IsParallel=true) annotations can’t be used together on the same Apex method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Loading Test Data

A

Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code.
Follow these steps:
Add the data in a .csv file.
Create a static resource for this file.
Call Test.loadData within your test method and passing it the sObject type token and the static resource name.
For example, for Account records and a static resource name of myResource, make the following call:
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');
The Test.loadData method returns a list of sObjects that correspond to each record inserted.</sObject>

You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a .csv extension. The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent lines are the field values.

Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are:
text/csv
application/vnd.ms-excel
application/octet-stream
text/plain
Test.loadData Example
The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records.
Create a .csv file that has the data for the test records. This sample .csv file has three account records. You can use this sample content to create your .csv file.
Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry
sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San Francisco,CA,94105,US
sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite 300,San Francisco,CA,94105,US
sForceTest3,http://www.sforcetest3.com,(415) 901-7000,1 Market St,San Francisco,CA,94105,US
Create a static resource for the .csv file:
From Setup, enter Static Resources in the Quick Find box, then select Static Resources.
Click New.
Name your static resource testAccounts.
Choose the file you created.
Click Save.
Call Test.loadData in a test method to populate the test accounts.
@isTest
private class DataUtil {
static testmethod void testLoadData() {
// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
// Verify that all 3 test accounts were created
System.assert(ls.size() == 3);</sObject>

    // Get first test account
    Account a1 = (Account)ls[0];
    String acctName = a1.Name;
    System.debug(acctName);

    // Perform some testing using the test records
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Common Test Utility Classes for Test Data Creation

A

Common test utility classes are public test classes that contain reusable code for test data creation.
Public test utility classes are defined with the IsTest annotation, and as such, are excluded from the organization code size limit and execute in test context. They can be called by test methods but not by non-test code.

The methods in the public test utility class are defined the same way methods are in non-test classes. They can take parameters and can return a value. The methods must be declared as public or global to be visible to other test classes. These common methods can be called by any test method in your Apex classes to set up test data before running the test. While you can create public methods for test data creation in a regular Apex class, without the IsTest annotation, you don’t get the benefit of excluding this code from the organization code size limit.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Using Test Setup Methods

A

Use test setup methods (methods that are annotated with @testSetup) to create test records once and then access them in every test method in the test class. Test setup methods can be time-saving when you need to create reference or prerequisite data for all test methods, or a common set of records that all test methods operate on.
Test setup methods can reduce test execution times especially when you’re working with many records. Test setup methods enable you to create common test data easily and efficiently. By setting up records once for the class, you don’t need to re-create records for each test method. Also, because the rollback of records that are created during test setup happens at the end of the execution of the entire class, the number of records that are rolled back is reduced. As a result, system resources are used more efficiently compared to creating those records and having them rolled back for each test method.

If a test class contains a test setup method, the testing framework executes the test setup method first, before any test method in the class. Records that are created in a test setup method are available to all test methods in the test class and are rolled back at the end of test class execution. If a test method changes those records, such as record field updates or record deletions, those changes are rolled back after each test method finishes execution. The next executing test method gets access to the original unmodified state of those records.

Syntax
Test setup methods are defined in a test class, take no arguments, and return no value. The following is the syntax of a test setup method.

@testSetup static void methodName() {

}

Test Setup Method Considerations
* Test setup methods are supported only with the default data isolation mode for a test class. If the test class or a test method has access to organization data by using the @isTest(SeeAllData=true) annotation, test setup methods aren’t supported in this class. Because data isolation for tests is available for API versions 24.0 and later, test setup methods are also available for those versions only.
* You can have only one test setup method per test class.
* If a fatal error occurs during the execution of a test setup method, such as an exception that’s caused by a DML operation or an assertion failure, the entire test class fails, and no further tests in the class are executed.
* If a test setup method calls a non-test method of another class, no code coverage is calculated for the non-test method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Run Unit Test Methods

A

To verify the functionality of your Apex code, execute unit tests. You can run Apex test methods in the Developer Console, in Setup, in the Salesforce extensions for Visual Studio Code, or using the API.
You can run these groupings of unit tests.
* Some or all methods in a specific class
* Some or all methods in a set of classes
* A predefined suite of classes, known as a test suite
* All unit tests in your org
*
To run a test, use any of the following:
* Salesforce user interface
* Salesforce extensions for Visual Studio Code and Code Builder
* Developer Console
* The API
All Apex tests that are started from the Salesforce user interface (including the Developer Console) run asynchronously and in parallel. Apex test classes are placed in the Apex job queue for execution. The maximum number of test classes that you can run per 24-hour period is the greater of 500 or 10 multiplied by the number of test classes in the org. For sandbox and Developer Edition organizations, this limit is higher and is the greater of 500 or 20 multiplied by the number of test classes in the org.

Apex tests that run as part of a deployment always run synchronously and serially.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Running Tests Through the Salesforce User Interface

A

You can run unit tests on the Apex Test Execution page. Tests started on this page run asynchronously, that is, you don’t have to wait for a test class execution to finish. The Apex Test Execution page refreshes the status of a test and displays the results after the test completes.

From Setup, enter Apex Test Execution in the Quick Find box, then select Apex Test Execution.
Click Select Tests….
Select the tests to run. The list of tests includes only classes that contain test methods.
Note
If you have Apex classes that are installed from a managed package, you must compile these classes first by clicking Compile all classes on the Apex Classes page so that they appear in the list.

To select tests from an installed managed package, select the managed package’s corresponding namespace from the dropdown list. Only the classes of the managed package with the selected namespace appear in the list.
To select tests that exist locally in your organization, select [My Namespace] from the dropdown list. Only local classes that aren’t from managed packages appear in the list.
To select any test, select [All Namespaces] from the dropdown list. All the classes in the organization appear, even those in a managed package.
Note
Classes with tests currently running don’t appear in the list.

To opt out of collecting code coverage information during test runs, select Skip Code Coverage.
Click Run.
After you run tests using the Apex Test Execution page, you can view code coverage details in the Developer Console.

From Setup, enter Apex in the Quick Find box, select Apex Test Execution, then click View Test History to view all test results for your organization, not just tests that you have run. Test results are retained for 30 days after they finish running, unless cleared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Running Tests Using the Developer Console

A

In the Developer Console, you can execute some or all tests in specific test classes, set up and run test suites, or run all tests. The Developer Console runs tests asynchronously in the background, unless your test run includes only one class and you’ve not chosen Always Run Asynchronously in the Test menu. Running tests asynchronously lets you work in other areas of the Developer Console while tests are running. After the tests execute, you can inspect the test results in the Developer Console. Also, you can inspect the overall code coverage for classes covered by the tests.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Running Tests Using the API

A

You can use the runTests() call from SOAP API to run tests synchronously.
RunTestsResult[] runTests(RunTestsRequest ri)
This call allows you to run the following, as specified in the RunTestsRequest object:

All tests in all classes
All tests in a specific namespace
All tests in a subset of classes in a specific namespace
It returns the following:

Total number of tests that ran
Code coverage statistics
Error information for each failed test
Information for each test that succeeds
Time it took to run the test
For more information on runTests(), see runTests() in the SOAP API Developer Guide.

You can also run tests using the Tooling REST API. Use the /runTestsAsynchronous/ and /runTestsSynchronous/ endpoints to run tests asynchronously or synchronously. For usage details, see Tooling API: REST Resources.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Running Tests Using ApexTestQueueItem

A

You can run tests asynchronously using ApexTestQueueItem and ApexTestResult. These objects let you add tests to the Apex job queue and check the results of the completed test runs. This process enables you to not only start tests asynchronously but also schedule your tests to execute at specific times by using the Apex scheduler. See Apex Scheduler for more information.

Insert an ApexTestQueueItem object to place its corresponding Apex class in the Apex job queue for execution. The Apex job executes the test methods in the class. After the job executes, ApexTestResult contains the result for each single test method executed as part of the test.

ApexTestResult rows are also generated for Apex tests run with the @testSetup annotation. The IsTestSetup field is set to true for these annotated tests to distinguish them from other test methods. The TestSetupTime field on ApexTestRunResult tracks the cumulative time of all setup methods for the given ApexTestRunResult.

To abort a class that is in the Apex job queue, perform an update operation on the ApexTestQueueItem object and set its Status field to Aborted.

If you insert multiple Apex test queue items in a single bulk operation, the queue items share a parent job and a test run can execute tests for several classes.

The maximum number of test queue items, and hence classes, that you can insert in the Apex job queue is the greater of 500 or 10 multiplied by the number of test classes in the org. For sandbox and Developer Edition organizations, this limit is higher and is the greater of 500 or 20 multiplied by the number of test classes in the org.

This example uses DML operations to insert and query the ApexTestQueueItem and ApexTestResult objects. The enqueueTests method inserts queue items for all classes that end with Test. It then returns the parent job ID of one queue item, which is the same for all queue items because they were inserted in bulk. The checkClassStatus method retrieves all queue items that correspond to the specified job ID. It then queries and outputs the name, job status, and pass rate for each class. The checkMethodStatus method gets information of each test method that was executed as part of the job.
// Enqueue all classes ending in “Test”.
public static ID enqueueTests() {
ApexClass[] testClasses =
[SELECT Id FROM ApexClass
WHERE Name LIKE ‘%Test’];
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}</ApexTestQueueItem>

        insert queueItems;

        // Get the job ID of the first queue item returned.
        ApexTestQueueItem item = 
           [SELECT ParentJobId FROM ApexTestQueueItem 
            WHERE Id=:queueItems[0].Id LIMIT 1];
        return item.parentjobid;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Using the runAs Method

A

Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user aren’t taken into account. The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method enforces record sharing. User permissions and field-level permissions are applied for the new context user as described in Enforcing Object and Field Permissions.

The user’s record sharing and object and field permissions are enforced within a runAs block, regardless of the sharing mode of the test class. If a user-defined method is called in the runAs block, the sharing mode enforced is that of the class where the method is defined.

You can use runAs only in test methods. The original system context is started again after all runAs test methods complete.

The runAs method ignores user license limits. You can create users with runAs even if your organization has no additional user licenses.

Every call to runAs counts against the total number of DML statements issued in the process.

In the following example, a new test user is created, then code is run as that user, with that user’s record sharing access:
@isTest
private class TestRunAs {
public static testMethod void testRunAs() {
// Setup test data
// Create a unique UserName
String uniqueUserName = ‘standarduser’ + DateTime.now().getTime() + ‘@testorg.com’;
// This code runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
User u = new User(Alias = ‘standt’, Email=’standarduser@testorg.com’,
EmailEncodingKey=’UTF-8’, LastName=’Testing’, LanguageLocaleKey=’en_US’,
LocaleSidKey=’en_US’, ProfileId = p.Id,
TimeZoneSidKey=’America/Los_Angeles’,
UserName=uniqueUserName);

    System.runAs(u) {
          // The following code runs as user 'u'
          System.debug('Current User: ' + UserInfo.getUserName());
          System.debug('Current Profile: ' + UserInfo.getProfileId());
      }
} }

Other Uses of runAs
You can also use the runAs method to perform mixed DML operations in your test by enclosing the DML operations within the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations.

There’s another overload of the runAs method (runAs(System.Version)) that takes a package version as an argument. This method causes the code of a specific version of a managed package to be used. For information on using the runAs method and specifying a package version context, see Testing Behavior in Package Versions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Using Limits, startTest, and stopTest

A

The Limits methods return the specific limit for the particular governor, such as the number of calls of a method or the amount of heap size remaining.

Each method has two versions. The first version returns the amount of the resource that has been used in the current context. The second version contains the word “limit” and returns the total amount of the resource that is available for that context. For example, getCallouts returns the number of callouts to an external service that have already been processed in the current context, while getLimitCallouts returns the total number of callouts available in the given context.

In addition to the Limits methods, use the startTest and stopTest methods to validate how close the code is to reaching governor limits.

The startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once. All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits.

The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement, the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the original context, and can only make 2 additional SOQL queries before reaching the limit of 100.

The stopTest method marks the point in your test code when your test ends. Use this method in conjunction with the startTest method. Each test method is allowed to call this method only once. Any code that executes after the stopTest method is assigned the original limits that were in effect before startTest was called. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. An exception encountered during stopTest halts the synchronous processing. For example, an unhandled exception in a batch job’s execute method will prevent the finish method from running in a test context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Adding SOSL Queries to Unit Tests

A

To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of record IDs, any SOSL queries that take place later in the test method return an empty list of results.

The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query, they are applied to the list of fixed search results. For example:
@isTest
private class SoslFixedResultsTest1 {

public static testMethod void testSoslFixedResults() {
   Id [] fixedSearchResults= new Id[1];
   fixedSearchResults[0] = '001x0000003G89h';
   Test.setFixedSearchResults(fixedSearchResults);
   List<List<SObject>> searchList = [FIND 'test' 
                                     IN ALL FIELDS RETURNING 
                                        Account(id, name WHERE name = 'test' LIMIT 1)];
} } Although the account record with an ID of 001x0000003G89h may not match the query string in the FIND clause ('test'), the record is passed into the RETURNING clause of the SOSL statement. If the record with ID 001x0000003G89h matches the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Best Practices for Parallel Test Execution

A

Tests that are started from the Salesforce user interface (including the Developer Console) run in parallel. Parallel test execution can speed up test run time. Sometimes, parallel test execution results in data contention issues, and you can turn off parallel execution in those cases. In particular, data contention issues and UNABLE_TO_LOCK_ROW errors can occur in the following cases:
When tests update the same records at the same time. Updating the same records typically occurs when tests don’t create their own data and turn off data isolation to access the organization’s data.
When a deadlock occurs in tests that are running in parallel and that try to create records with duplicate index field values. A deadlock occurs when two running tests are waiting for each other to roll back data. Such a wait can happen if two tests insert records with the same unique index field values.
You can prevent receiving those errors by turning off parallel test execution in the Salesforce user interface:
From Setup, enter Apex Test.
Click Options….
In the Apex Test Execution Options dialog, select Disable Parallel Apex Testing and then click OK.
Test classes annotated with IsTest(IsParallel=true) indicate that the test class can run concurrently with more than the default number of concurrent test classes. This annotation overrides default settings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Inspecting Code Coverage

A

After running tests, you can view code coverage information in the Tests tab of the Developer Console. The code coverage pane includes coverage information for each Apex class and the overall coverage for all Apex code in your organization.

Also, code coverage is stored in two Lightning Platform Tooling API objects: ApexCodeCoverageAggregate and ApexCodeCoverage. ApexCodeCoverageAggregate stores the sum of covered lines for a class after checking all test methods that test it. ApexCodeCoverage stores the lines that are covered and uncovered by each individual test method. For this reason, a class can have multiple coverage results in ApexCodeCoverage—one for each test method that has tested it. You can query these objects by using SOQL and the Tooling API to retrieve coverage information. Using SOQL queries with Tooling API is an alternative way of checking code coverage and a quick way to get more details.

SELECT ApexClassOrTrigger.Name, NumLinesCovered, NumLinesUncovered
FROM ApexCodeCoverageAggregate
WHERE ApexClassOrTrigger.Name = ‘TaskUtil’
This SOQL query requires the Tooling API. You can run this query by using the Query Editor in the Developer Console and checking Use Tooling API.

SELECT ApexTestClass.Name,TestMethodName,NumLinesCovered,NumLinesUncovered
FROM ApexCodeCoverage
WHERE ApexClassOrTrigger.Name = ‘TaskUtil’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Build a Mocking Framework with the Stub API

A

Apex provides a stub API for implementing a mocking framework. A mocking framework has many benefits. It can streamline and improve testing and help you create faster, more reliable tests. You can use it to test classes in isolation, which is important for unit testing. Building your mocking framework with the stub API can also be beneficial because stub objects are generated at runtime. Because these objects are generated dynamically, you don’t have to package and deploy test classes. You can build your own mocking framework, or you can use one built by someone else.
You can define the behavior of stub objects, which are created at runtime as anonymous subclasses of Apex classes. The stub API comprises the System.StubProvider interface and the System.Test.createStub() method.
Let’s say we want to test the formatting method in the following class.
ublic class DateFormatter {
// Method to test
public String getFormattedDate(DateHelper helper) {
return ‘Today's date is ‘ + helper.getTodaysDate();
}
}

public class DateHelper {
// Method to stub
public String getTodaysDate() {
return Date.today().format();
}
}
DateFormatter df = new DateFormatter();
DateHelper dh = new DateHelper();
String dateStr = df.getFormattedDate(dh);

For testing, we want to isolate the getFormattedDate() method to make sure that the formatting is working properly. The return value of the getTodaysDate() method normally varies based on the day. However, in this case, we want to return a constant, predictable value to isolate our testing to the formatting. Rather than writing a “fake” version of the class, where the method returns a constant value, we create a stub version of the class. The stub object is created dynamically at runtime, and we can specify the “stubbed” behavior of its method.

To use a stub version of an Apex class:
Define the behavior of the stub class by implementing the System.StubProvider interface.
Instantiate a stub object by using the System.Test.createStub() method.
Invoke the relevant method of the stub object from within a test class.

Implement the StubProvider Interface:
@isTest
public class MockProvider implements System.StubProvider {

public Object handleMethodCall(Object stubbedObject, String stubbedMethodName, 
    Type returnType, List<Type> listOfParamTypes, List<String> listOfParamNames, 
    List<Object> listOfArgs) {
    
    // The following debug statements show an example of logging 
    // the invocation of a mocked method.
   
    // You can use the method name and return type to determine which method was called.
    System.debug('Name of stubbed method: ' + stubbedMethodName);
    System.debug('Return type of stubbed method: ' + returnType.getName());
    
    // You can also use the parameter names and types to determine which method 
    // was called.
    for (integer i =0; i < listOfParamNames.size(); i++) {
        System.debug('parameter name: ' + listOfParamNames.get(i));
        System.debug('  parameter type: ' + listOfParamTypes.get(i).getName());
    }
    
    // This shows the actual parameter values passed into the stubbed method at runtime.
    System.debug('number of parameters passed into the mocked call: ' + 
        listOfArgs.size());
    System.debug('parameter(s) sent into the mocked call: ' + listOfArgs);
    
    // This is a very simple mock provider that returns a hard-coded value 
    // based on the return type of the invoked.
    if (returnType.getName() == 'String')
        return '8/8/2016';
    else 
        return null;
} } StubProvider is a callback interface. It specifies a single method that requires implementing: handleMethodCall(). When a stubbed method is called, handleMethodCall() is called. You define the behavior of the stubbed class in this method. The method has the following parameters.

Instantiate a Stub Version of the Class:
public class MockUtil {
private MockUtil(){}

public static MockProvider getInstance() {
    return new MockProvider();
}

 public static Object createMock(Type typeToMock) {
    // Invoke the stub API and pass it our mock provider to create a 
    // mock class of typeToMock.
    return Test.createStub(typeToMock, MockUtil.getInstance());
} }

Invoke the Stub Method:
@isTest
public class DateFormatterTest {
@isTest
public static void testGetFormattedDate() {
// Create a mock version of the DateHelper class.
DateHelper mockDH = (DateHelper)MockUtil.createMock(DateHelper.class);
DateFormatter df = new DateFormatter();

    // Use the mocked object in the test.
    System.assertEquals('Today\'s date is 8/8/2016', df.getFormattedDate(mockDH));
} }

Apex Stub API Limitations
Keep the following limitations in mind when working with the Apex stub API.

  • The object being mocked must be in the same namespace as the call to the Test.createStub() method. However, the implementation of the StubProvider interface can be in another namespace.
  • Iterators can’t be used as return types or parameter types.
  • You can’t mock the following Apex elements.
    Static methods (including future methods)
    Private methods
    Properties (getters and setters)
    Triggers
    Inner classes
    System types
    Classes that implement the Batchable interface
    Classes that have only private constructors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Debug Log

A

A debug log can record database operations, system processes, and errors that occur when executing a transaction or running unit tests. Debug logs can contain information about:
Database changes
HTTP callouts
Apex errors
Resources used by Apex
Automated workflow processes, such as: Workflow rules, Assignment rules, Approval processes, Validation rules

The debug log doesn’t include information from actions triggered by time-based workflows.

You can retain and manage debug logs for specific users, including yourself, and for classes and triggers. Setting class and trigger trace flags doesn’t cause logs to be generated or saved. Class and trigger trace flags override other logging levels, including logging levels set by user trace flags, but they don’t cause logging to occur. If logging is enabled when classes or triggers execute, logs are generated at the time of execution.

To view a debug log from Setup, enter Debug Logs in the Quick Find box, then select Debug Logs. Then click View next to the debug log that you want to examine. Click Download to download the log as an XML file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Debug Log Limits

A

Debug logs have the following limits.

Each debug log must be 20 MB or smaller. Debug logs that are larger than 20 MB are reduced in size by removing older log lines, such as log lines for earlier System.debug statements. The log lines can be removed from any location, not just the start of the debug log.
System debug logs are retained for 24 hours. Monitoring debug logs are retained for seven days.
If you generate more than 1,000 MB of debug logs in a 15-minute window, your trace flags are disabled. We send an email to the users who last modified the trace flags, informing them that they can re-enable the trace flag in 15 minutes.
Warning
If the debug log trace flag is enabled on a frequently accessed Apex class or for a user executing requests often, the request can result in failure, regardless of the time window and the size of the debug logs.

When your org accumulates more than 1,000 MB of debug logs, we prevent users in the org from adding or editing trace flags. To add or edit trace flags so that you can generate more logs after you reach the limit, delete some debug logs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Inspecting the Debug Log Sections

A

After you generate a debug log, the type and amount of information listed depends on the filter values you set for the user. However, the format for a debug log is always the same.
Session IDs are replaced with “SESSION_ID_REMOVED” in Apex debug logs

A debug log has the following sections.
Header
The header contains the following information.
The version of the API used during the transaction.
The log category and level used to generate the log. For example:
The following is an example of a header: 61.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO

In this example, the API version is 61.0, and the following debug log categories and levels have been set.
Apex Code DEBUG
Apex Profiling INFO
Callout INFO
Database INFO
System DEBUG
Validation INFO
Visualforce INFO
Workflow INFO

Warning
If the Apex Code log level is set to FINEST, the debug log includes details of all Apex variable assignments. Ensure that the Apex Code being traced doesn’t handle sensitive data. Before enabling FINEST log level, be sure to understand the level of sensitive data your organization’s Apex handles. Be careful with processes such as community users self-registration where user passwords can be assigned to an Apex string variable.

Execution Units
An execution unit is equivalent to a transaction. It contains everything that occurred within the transaction. EXECUTION_STARTED and EXECUTION_FINISHED delimit an execution unit.
Code Units
A code unit is a discrete unit of work within a transaction. For example, a trigger is one unit of code, as is a webservice method or a validation rule. CODE_UNIT_STARTED and CODE_UNIT_FINISHED delimit units of code. Units of work can embed other units of work. For example:
EXECUTION_STARTED
CODE_UNIT_STARTED|[EXTERNAL]execute_anonymous_apex
CODE_UNIT_STARTED|[EXTERNAL]MyTrigger on Account trigger event BeforeInsert for [new]|sfdc_trigger/MyTrigger
CODE_UNIT_FINISHED <– The trigger ends
CODE_UNIT_FINISHED <– The executeAnonymous ends
EXECUTION_FINISHED
Units of code include, but aren’t limited to, the following:
Triggers
Workflow invocations and time-based workflow
Validation rules
Approval processes
Apex lead convert
@future method invocations
Web service invocations
executeAnonymous calls
Visualforce property access on Apex controllers
Visualforce actions on Apex controllers
Execution of the batch Apex start and finish methods, and each execution of the execute method
Execution of the Apex System.Schedule execute method
Incoming email handling
Log Lines
Log lines are included inside units of code and indicate which code or rules are being executed. Log lines can also be messages written to the debug log.
More Log Data
In addition, the log contains the following information.
Cumulative resource usage is logged at the end of many code units. Among these code units are triggers, executeAnonymous, batch Apex message processing, @future methods, Apex test methods, Apex web service methods, and Apex lead convert.
Cumulative profiling information is logged once at the end of the transaction and contains information about DML invocations, expensive queries, and so on. “Expensive” queries use resources heavily.
Heap usage is accurately reported in the debug log and an exception is thrown whenever an Apex Heap Size error occurs. At other times, the heap size shown in the debug log is the largest heap size that was calculated during the transaction. To reduce the overhead on small transactions, minimal heap usage doesn’t warrant an accurate calculation and is reported as 0(zero).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Setting Debug Log Filters for Apex Classes and Triggers

A

Debug log filtering provides a mechanism for fine-tuning the log verbosity at the trigger and class level. This is especially helpful when debugging Apex logic. For example, to evaluate the output of a complex process, you can raise the log verbosity for a given class while turning off logging for other classes or triggers within a single request.

When you override the debug log levels for a class or trigger, these debug levels also apply to the class methods that your class or trigger calls and the triggers that get executed as a result. All class methods and triggers in the execution path inherit the debug log settings from their caller, unless they have these settings overridden.

The following diagram illustrates overriding debug log levels at the class and trigger level. For this scenario, suppose Class1 is causing some issues that you want to take a closer look at. To this end, the debug log levels of Class1 are raised to the finest granularity. Class3 doesn’t override these log levels, and therefore inherits the granular log filters of Class1. However, UtilityClass has already been tested and is known to work properly, so it has its log filters turned off. Similarly, Class2 isn’t in the code path that causes a problem, therefore it has its logging minimized to log only errors for the Apex Code category. Trigger2 inherits these log settings from Class2.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

New Trace Flag
Setup > Debug Logs

A

To specify the type of information that is included in debug logs, add trace flags and debug levels. Each trace flag includes a debug level, a start time, an end time, and a log type.

Trace flags set logging levels (such as for Database, Workflow, and Validation) for a user, Apex class, or Apex trigger for up to 24 hours.

Select Automated Process from the dropdown list to set a trace flag on the automated process user. The automated process user runs background jobs, such as emailing Chatter invitations.
Select Platform Integration from the dropdown list to set a trace flag on the platform integration user. The platform integration user runs processes in the background, and appears in audit fields of certain records, such as cases created by the Einstein Bot.
Select User from the dropdown list to specify a user whose debug logs you’d like to monitor and retain.
Select Apex Class or Apex Trigger from the dropdown list to specify the log levels that take precedence while executing a specific Apex class or trigger. Setting class and trigger trace flags doesn’t cause logs to be generated or saved. Class and trigger trace flags override other logging levels, including logging levels set by user trace flags, but they don’t cause logging to occur. If logging is enabled when classes or triggers execute, logs are generated at the time of execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Working with Logs in the Developer Console

A

Use the Logs tab in the Developer Console to open debug logs.
Logs open in Log Inspector. Log Inspector is a context-sensitive execution viewer in the Developer Console. It shows the source of an operation, what triggered the operation, and what occurred next. Use this tool to inspect debug logs that include database events, Apex processing, workflow, and validation logic.

When using the Developer Console or monitoring a debug log, you can specify the level of information that gets included in the log.
Log category
The type of information logged, such as information from Apex or workflow rules.
Log level
The amount of information logged.
Event type
The combination of log category and log level that specify which events get logged. Each event can log additional information, such as the line and character number where the event started, fields associated with the event, and duration of the event.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Debug Log Categories

A

Each debug level includes a debug log level for each of the following log categories. The amount of information logged for each category depends on the log level.
Log Category
Database Includes information about database activity, including every data manipulation language (DML) statement or inline SOQL or SOSL query.
Workflow Includes information for workflow rules, flows, and processes, such as the rule name and the actions taken.
NBA Includes information about Einstein Next Best Action activity, including strategy execution details from Strategy Builder.
Validation Includes information about validation rules, such as the name of the rule and whether the rule evaluated true or false.
Callout Includes the request-response XML that the server is sending and receiving from an external web service. Useful when debugging issues related to using Lightning Platform web service API calls or troubleshooting user access to external objects via Salesforce Connect.
Apex Code Includes information about Apex code. Can include information such as log messages generated by DML statements, inline SOQL or SOSL queries, the start and completion of any triggers, and the start and completion of any test method.
Apex Profiling Includes cumulative profiling information, such as the limits for your namespace and the number of emails sent.
Visualforce Includes information about Visualforce events, including serialization and deserialization of the view state or the evaluation of a formula field in a Visualforce page.
System Includes information about calls to all system methods such as the System.debug method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Debug Log Levels

A

Each debug level includes one of the following log levels for each log category. The levels are listed from lowest to highest. Specific events are logged based on the combination of category and levels. Most events start being logged at the INFO level. The level is cumulative, that is, if you select FINE, the log also includes all events logged at the DEBUG, INFO, WARN, and ERROR levels.
Note Not all levels are available for all categories. Only the levels that correspond to one or more events are available.

NONE
ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST
Important

Before running a deployment, verify that the Apex Code log level isn’t set to FINEST. Otherwise, the deployment is likely to take longer than expected. If the Developer Console is open, the log levels in the Developer Console affect all logs, including logs created during a deployment.

30
Q

Debug Event Types

A

The following is an example of what is written to the debug log. The event is USER_DEBUG. The format is timestamp | event identifier:
timestamp: Consists of the time when the event occurred and a value between parentheses. The time is in the user’s time zone and in the format HH:mm:ss.SSS. The value in parentheses represents the time elapsed in nanoseconds since the start of the request. The elapsed time value is excluded from logs reviewed in the Developer Console when you use the Execution Log view. However, you can see the elapsed time when you use the Raw Log view. To open the Raw Log view, from the Developer Console’s Logs tab, right-click the name of a log and select Open Raw Log.
event identifier: Specifies the event that triggered the debug log entry (such as SAVEPOINT_RESET or VALIDATION_RULE).
Also includes additional information logged with that event, such as the method name or the line and character number where the code was executed. If a line number can’t be located, [EXTERNAL] is logged instead. For example, [EXTERNAL] is logged for built-in Apex classes or code that’s in a managed package.

For some events (CODE_UNIT_STARTED, CODE_UNIT_FINISHED, VF_APEX_CALL_START, VF_APEX_CALL_END, CONSTRUCTOR_ENTRY, and CONSTRUCTOR_EXIT), the end of the event identifier includes a pipe (|) followed by a typeRef for an Apex class or trigger.

For a trigger, the typeRef begins with the SFDC trigger prefix sfdc_trigger/. For example, sfdc_trigger/YourTriggerName or sfdc_trigger/YourNamespace/YourTriggerName.

For a class, the typeRef uses the format YourClass, YourClass$YourInnerClass, or YourNamespace/YourClass$YourInnerClass.

Example:

15:51:01.071 (55856000)|DML_BEGIN|[5]|Op:Insert|Type:Invoice_Statement_c| Rows:1
EventName - DML_BEGIN, Line number of the event in the code: - [5] DML operation type—Insert: Op:Insert, Object name: Type:Invoice_Statement_c , Number of rows passed into the DML operation: Rows:1

31
Q

Debugging Apex API Calls

A

All API calls that invoke Apex support a debug facility that allows access to detailed information about the execution of the code, including any calls to System.debug(). The categories field of a SOAP input header called DebuggingHeader allows you to set the logging granularity according to the levels outlined in this table.
category - Specify the type of information returned in the debug log. Valid values are:
Db
Workflow
Validation
Callout
Apex_code
Apex_profiling
Visualforce
System
All
level - Specifies the level of detail returned in the debug log.
Valid log levels are (listed from lowest to highest):
NONE
ERROR
WARN
INFO
DEBUG
FINE
FINER
FINEST

32
Q

Debug Log Order of Precedence

A

Which events are logged depends on various factors. These factors include your trace flags, the default logging levels, your API header, user-based system log enablement, and the log levels set by your entry points.
The order of precedence for debug log levels is:
1. Trace flags override all other logging logic. The Developer Console sets a trace flag when it loads, and that trace flag remains in effect until it expires. You can set trace flags in the Developer Console or in Setup or by using the TraceFlag and DebugLevel Tooling API objects.
2. If you don’t have active trace flags, synchronous and asynchronous Apex tests execute with the default logging levels. Default logging levels are:
DB - INFO
APEX_CODE - DEBUG
APEX_PROFILING - INFO
WORKFLOW - INFO
VALIDATION - INFO
CALLOUT - INFO
VISUALFORCE - INFO
SYSTEM - DEBUG
3. If no relevant trace flags are active, and no tests are running, your API header sets your logging levels. API requests that are sent without debugging headers generate transient logs—logs that aren’t saved—unless another logging rule is in effect.
4. If your entry point sets a log level, that log level is used. For example, Visualforce requests can include a debugging parameter that sets log levels.
If none of these cases apply, logs aren’t generated or persisted.

33
Q

Delete Debug Logs

A

When your org accumulates too many debug logs, delete some or all of your system logs and monitoring logs. Use the Developer Console’s Query Editor to find and delete the logs using Tooling API.
Open Developer Console.
At the bottom of the console, select the Query Editor tab.
Select Use Tooling API.
Enter this SOQL query:
SELECT Id, StartTime, LogUserId, LogLength, Location FROM ApexLog
Click Execute.
Select the logs you want to delete. To sort by a column, click its header. To select individual logs, press Ctrl (Windows or Linux) or Command (macOS). To select a block of logs, press Shift.
LogLength shows the size of the log in bytes.

For system logs, Location is SystemLog. System logs are generated as part of system log monitoring, such as while you use Developer Console, and are visible only to you.

For monitoring logs, Location is Monitoring. Monitoring logs are generated when your org has active CLASS_TRACING or USER_DEBUG trace flags. These logs are visible to all your org’s admins.

Each debug log must be 20 MB or smaller. Debug logs that are larger than 20 MB are reduced in size by removing older log lines, such as log lines for earlier System.debug statements. The log lines can be removed from any location, not just the start of the debug log.
System debug logs are retained for 24 hours. Monitoring debug logs are retained for seven days.
If you generate more than 1,000 MB of debug logs in a 15-minute window, your trace flags are disabled. We send an email to the users who last modified the trace flags, informing them that they can re-enable the trace flag in 15 minutes.
Warning
WARNING If the debug log trace flag is enabled on a frequently accessed Apex class or for a user executing requests often, the request can result in failure, regardless of the time window and the size of the debug logs.
When your org accumulates more than 1,000 MB of debug logs, we prevent users in the org from adding or editing trace flags. To add or edit trace flags so that you can generate more logs after you reach the limit, delete some debug logs.
Click Delete Row.
To confirm the log deletion, click Yes.

34
Q

What Is the Developer Console?

A

The Developer Console is an integrated development environment with a collection of tools you can use to create, debug, and test applications in your Salesforce org.
Functions:
1. Debugging and Troubleshooting - View Logs(Open logs in the Log Inspector), Set and View Checkpoints in Apex Code (While the Developer Console can’t pause execution like a traditional debugger, it provides much of the same visibility and reduces the need to add System.debug statements)
2. Editing and Navigating Source Code - Browse Packages in Your Organization, View and Edit Apex Classes and Triggers, View and Edit Lightning Components, View and Edit Visualforce Pages and Components, Use the Source Code Editor, Format Your Code Files.
3. Testing and Validating Performance - Test Apex Code, Inspect Logs for Performance Issues - The Limits panel provides a summary view of resources used and maps them against your allocated request limits.
4. Executing SOQL and SOSL Queries - Query Editor, View Query Results

35
Q

Developer Console User Interface: Workspace

A

A workspace is a collection of resources represented by tabs in the main panel of the Developer Console. The detail view or editor shown in each tab is determined by the type of resource open in the tab. For example, source code opens in the Source Code Editor, logs open in the Log Inspector, and so on.

You can create a workspace for any group of resources that you use together to keep your work organized. For example, you can create one workspace for source code and another for debug logs, switching between them as you code and test.

The Workspace menu includes all the necessary links:

Switch Workspace: Allows you to select from your org’s saved workspaces.
New Workspace: Creates a new workspace. Enter a name for the workspace and click OK. Open the resources that you want in the workspace. The workspace will be saved when you switch to a different workspace or close the Developer Console.
Rename Current Workspace: Overwrites the current workspace with the name you enter.
Workspace Manager: Opens a popup window that allows you to browse, open, create, and delete your org’s workspaces.
You can open the following types of resources in the Developer Console workspace:

Logs open in the Log Inspector.
Checkpoints open in the Checkpoint Inspector.
Apex classes and triggers, and Visualforce pages and components open in the Source Code Editor.
Organization metadata and other non-code resources open in the Object Inspector.
Query results listed on the Query Editor tab open in an editable Query Results grid.
Finished test runs listed on the Tests tab open in a Test Results view.
To collapse unused panels, use the Collapse down buttonCollapse up buttonCollapse right buttonCollapse left button buttons. When collapsed, you can click a panel to temporarily reveal and use it. When your cursor moves out of the panel, it collapses automatically.

When you switch to a different workspace or close the Developer Console, the state of the tabs (and the panels within the tabs) in the current workspace is saved. If you have not created a workspace, the configuration is saved as the Default workspace.

Navigating Between Tabs
To move left and right through tabs in the workspace, click the appropriate tab or use the following keyboard shortcuts:

Left: CTRL+Page Up
Right: CTRL+Page Down
Navigating View History
To move backward and forward through your view history, click the Tab history buttons buttons or use the following keyboard shortcuts:

Backward: CTRL+,
Forward: CTRL+.
Clicking back button (or CTRL+) moves through the previously viewed tabs in the order that you viewed them. The forward button button only becomes active when you are viewing your history.

36
Q

Executing Anonymous Apex Code

A

The Execute Anonymous Apex tool in the Developer Console runs the Apex code you enter using ExecuteAnonymous and generates a debug log with the results of the execution.
WARNING If you call a class that contains a testMethod, all DML statements of the test method execute. This action can add unwanted data to your organization

37
Q

What Happens When an Exception Occurs?

A

When an exception occurs, code execution halts. Any DML operations that were processed before the exception are rolled back and aren’t committed to the database. Exceptions get logged in debug logs. For unhandled exceptions (exceptions that the code doesn’t catch) Salesforce sends an email that includes the exception information. The end user sees an error message in the Salesforce user interface.

38
Q

Unhandled Exception Emails

A

When unhandled Apex exceptions occur, emails sent contain the Apex stack trace, exception message, customer’s org and user ID, org name, and My Domain name. No other data is returned with the report. Unhandled exception emails are sent by default to the developer specified in the LastModifiedBy field on the failing class or trigger. In addition, you can have emails sent to users of your Salesforce org and to arbitrary email addresses. These email recipients can also receive process or flow error emails. To set up these email notifications, from Setup, enter Apex Exception Email in the Quick Find box, then select Apex Exception Email. The entered email addresses then apply to all managed packages in the customer’s org. You can also configure Apex exception emails using Tooling API object ApexEmailNotification.

Note

If duplicate exceptions occur in Apex code that runs synchronously or asynchronously, subsequent exception emails are suppressed and only the first email is sent. This email suppression prevents flooding of the developer’s inbox with emails about the same error.
Emails aren’t sent for exceptions encountered with anonymous Apex executions.
Apex exception emails are limited to 10 emails per hour, per application server. Because this limit isn’t on a per-org basis, email delivery to a particular org can be unreliable.

39
Q

Throw Statements

A

A throw statement allows you to signal that an error has occurred. To throw an exception, use the throw statement and provide it with an exception object to provide information about the specific error.
For example:
throw exceptionObject;

40
Q

Try-Catch-Finally Statements

A

The try, catch, and finally statements can be used to gracefully recover from a thrown exception:
The try statement identifies a block of code in which an exception can occur.
The catch statement identifies a block of code that can handle a particular type of exception. A single try statement can have zero or more associated catch statements. Each catch statement must have a unique exception type. Also, once a particular exception type is caught in one catch block, the remaining catch blocks, if any, aren’t executed.
The finally statement identifies a block of code that is guaranteed to execute and allows you to clean up your code. A single try statement can have up to one associated finally statement. Code in the finally block always executes regardless of whether an exception was thrown or the type of exception that was thrown. Because the finally block always executes, use it for cleanup code, such as for freeing up resources.
At least a catch block or a finally block must be present with a try block. The following is the syntax of a try-catch block.

try {
// Try block
code_block
} catch (exceptionType variableName) {
// Initial catch block.
// At least the catch block or the finally block must be present.
code_block
} catch (Exception e) {
// Optional additional catch statement for other exception types.
// Note that the general exception type, ‘Exception’,
// must be the last catch block when it is used.
code_block
} finally {
// Finally block.
// At least the catch block or the finally block must be present.
code_block
}

41
Q

Exceptions that Can’t be Caught

A

Some special types of built-in exceptions can’t be caught. Those exceptions are associated with critical situations in the Lightning Platform. These situations require the abortion of code execution and don’t allow for execution to resume through exception handling. One such exception is the limit exception (System.LimitException) that the runtime throws if a governor limit has been exceeded, such as when the maximum number of SOQL queries issued has been exceeded. Other examples are exceptions thrown when assertion statements fail (through System.assert methods) or license exceptions.

When exceptions are uncatchable, catch blocks, as well as finally blocks if any, aren’t executed.

42
Q

Error Exceptions: unreachable statements in code

A

In API version 41.0 and later, unreachable statements in your code will cause compilation errors. For example, the following code block generates a compile time error in API version 41.0 and later. The third statement can never be reached because the previous statement throws an unconditional exception.
Boolean x = true;
throw new NullPointerException();
x = false;

43
Q

Built-In Exceptions

A

DmlException - Any problem with a DML statement
ListException - Any problem with a list, such as attempting to access an index that is out of bounds.
NullPointerException - Any problem with dereferencing a null variable. This example creates a String variable named s but we don’t initialize it to a value, hence, it is null. Calling the contains method on our null variable causes a NullPointerException.
QueryException - Any problem with SOQL queries, such as assigning a query that returns no records or more than one record to a singleton sObject variable.
SObjectException - Any problem with sObject records, such as attempting to change a field in an update statement that can only be changed during insert.

44
Q

Common Exception Methods

A

You can use common exception methods to get more information about an exception, such as the exception error message or the stack trace.
Here are descriptions of some useful methods:
getCause: Returns the cause of the exception as an exception object.
getLineNumber: Returns the line number from where the exception was thrown.
getMessage: Returns the error message that displays for the user.
getStackTraceString: Returns the stack trace of a thrown exception as a string.
getTypeName: Returns the type of exception, such as DmlException, ListException, MathException, and so on.

Example

To find out what some of the common methods return, try running this example.

try {
Merchandise__c m = [SELECT Name FROM Merchandise__c LIMIT 1];
// Causes an SObjectException because we didn’t retrieve
// the Total_Inventory__c field.
Double inventory = m.Total_Inventory__c;
} catch(Exception e) {
System.debug(‘Exception type caught: ‘ + e.getTypeName());
System.debug(‘Message: ‘ + e.getMessage());
System.debug(‘Cause: ‘ + e.getCause()); // returns null
System.debug(‘Line number: ‘ + e.getLineNumber());
System.debug(‘Stack trace: ‘ + e.getStackTraceString());
}

More Exception Methods
Some exception types, such as DmlException, have specific exception methods that apply to only them and aren’t common to other exception types:

getDmlFieldNames(Index of the failed record): Returns the names of the fields that caused the error for the specified failed record.
getDmlId(Index of the failed record): Returns the ID of the failed record that caused the error for the specified failed record.
getDmlMessage(Index of the failed record): Returns the error message for the specified failed record.
getNumDml: Returns the number of failed records.

45
Q

Create Custom Exceptions

A

Exceptions can be top-level classes, that is, they can have member variables, methods and constructors, they can implement interfaces, and so on.

To create your custom exception class, extend the built-in Exception class and make sure your class name ends with the word Exception, such as “MyException” or “PurchaseException”. All exception classes extend the system-defined base class Exception, and therefore, inherits all common Exception methods.
public class MyException extends Exception {}

Here are some ways you can create your exceptions objects, which you can then throw.
You can construct exceptions:
new MyException();
new MyException(‘This is bad’);
With a single Exception argument that specifies the cause and that displays in any stack trace:
new MyException(e);
With both a String error message and a chained exception cause that displays in any stack trace:
new MyException(‘This is bad’, e);

46
Q

Rethrowing Exceptions and Inner Exceptions

A

After catching an exception in a catch block, you have the option to rethrow the caught exception variable. This is useful if your method is called by another method and you want to delegate the handling of the exception to the caller method. You can rethrow the caught exception as an inner exception in your custom exception and have the main method catch your custom exception type.

The following example shows how to rethrow an exception as an inner exception. The example defines two custom exceptions, My1Exception and My2Exception, and generates a stack trace with information about both.

// Define two custom exceptions
public class My1Exception extends Exception {}
public class My2Exception extends Exception {}

try {
// Throw first exception
throw new My1Exception(‘First exception’);
} catch (My1Exception e) {
// Throw second exception with the first
// exception variable as the inner exception
throw new My2Exception(‘Thrown with inner exception’, e);
}

47
Q

Debug Logs : When geneated?

A

Debug logs are generated when you have active user-based trace flags, when you run Apex tests, and when executed code or API requests include debugging parameters or headers.

48
Q

Debug Logs : What countains?

A

A debug log can record database operations, system processes, and errors that occur when executing a transaction or running unit tests. Debug logs can contain information about:
* Database changes
* HTTP callouts
* Apex errors
* Resources used by Apex
* Automated workflow processes, such as: Workflow rules, Assignment rules, Approval processes, Validation rules
Note
Note The debug log does not include information from actions triggered by time-based workflows.

49
Q

Developer Edition or Sandbox Environment?

A

A Developer Edition environment is a free, fully featured copy of the Enterprise Edition environment, with less storage and users. Developer Edition is a logically separate environment, ideal as your initial development environment. You can sign up for as many Developer Edition orgs as you need. This allows you to build an application designed for any of the Salesforce production environments.

A Partner Developer Edition is a licensed version of the free Developer Edition that includes more storage, features, and licenses. Partner Developer Editions are free to enrolled Salesforce partners.

Sandbox is a nearly identical copy of your production environment available to Professional, Enterprise, Performance, and Unlimited Edition customers. The sandbox copy can include data, configurations, or both. You can create multiple sandboxes in your production environments for a variety of purposes without compromising the data and applications in your production environment.

Developer Edition is ideal if you’re a:
1. Partner who intends to build a commercially available Salesforce app by creating a managed package for distribution through AppExchange or Trialforce. Only Developer Edition or Partner Developer Edition environments can create managed packages.
2. Salesforce customer with a Group or Personal Edition, and you don’t have access to Sandbox.
3. Developer looking to explore the Salesforce Platform for FREE!
Partner Developer Edition is ideal if you:
1. Are developing in a team and you require a team environment to manage all the source code. In this case, each developer has a Developer Edition environment and checks code in and out of this team repository environment.
2. Expect more than two developers to log in to develop and test.
3. Require a larger environment that allows more users to run robust tests against larger data sets.
Sandbox is ideal if you:
1. Are a Salesforce customer with Professional, Enterprise, Performance, Unlimited, or Salesforce Platform Edition, which includes Sandbox.
2. Are developing a Salesforce application specifically for your production environment.
3. Aren’t planning to build a Salesforce application to be distributed commercially. Have no intention to list on the AppExchange or distribute through Trialforce.

50
Q

What is a Sandbox

A

Sandboxes create copies of your Salesforce org in separate environments. Use them for development, testing, and training, without compromising the data and applications in your production org.

Salesforce offers sandboxes and a set of deployment tools, so you can:
* Isolate customization and development work from your production environment until you’re ready to deploy changes.
* Test changes against copies of your production data and users.
* Provide a training environment.
* Coordinate individual changes into one deployment to production.

51
Q

Sandbox Types

A

From Setup, enter Sandboxes in the Quick Find box, then select Sandboxes to view and manage your existing sandboxes or create new ones.

Sandbox Types
1. Developer Sandbox – A Developer sandbox is intended for development and testing in an isolated environment. A Developer Sandbox includes a copy of your production org’s configuration (metadata).
2. Developer Pro Sandbox – A Developer Pro sandbox is intended for development and testing in an isolated environment and can host larger data sets than a Developer sandbox. A Developer Pro sandbox includes a copy of your production org’s configuration (metadata). Use a Developer Pro sandbox to handle more development and quality assurance tasks and for integration testing or user training.
3. **Partial Copy Sandbox **– A Partial Copy sandbox is intended to be used as a testing environment. This environment includes a copy of your production org’s configuration (metadata) and a sample of your production org’s data as defined by a sandbox template. Use a Partial Copy sandbox for quality assurance tasks such as user acceptance testing, integration testing, and training.
4. Full Sandbox – A Full sandbox is intended to be used as a testing environment. Only Full sandboxes support performance testing, load testing, and staging. Full sandboxes are a replica of your production org, including all data, such as object records and attachments, and metadata. The length of the refresh interval makes it difficult to use Full sandboxes for development.

We recommend that you apply a sandbox template so that your sandbox contains only the records that you need for testing or other tasks.

When you create a Full sandbox, you also have to decide whether to include field tracking history and Chatter activity. Include it only if you require it for testing use cases.

The default is to omit field tracking.
Chatter activity data can be extensive, which can add a significant amount of time to your Full sandbox copy.

52
Q

Understanding Sandbox Refresh Intervals

A

The refresh interval for each sandbox environment is calculated from when the actual sandbox copying process begins. The sandbox status changes from Pending to Processing at the start of copying.

If other sandbox copy requests were made before yours, your sandbox sometimes remains in the Pending status for some time. The refresh interval timer for your sandbox doesn’t start until your request leaves this state.

Salesforce enforces specific refresh frequency limits on different types of sandboxes—Full Copy sandboxes can be refreshed every 29 days, Partial Copy every 5 days, and Developer/Developer Pro sandboxes once per day.

53
Q

Sandbox Licenses and Storage Limits by Type

A

Sandbox Type:
Developer Sandbox 1 day (Refresh Interval),
Storage Limit: Data storage: 200 MB, File storage: 200 MB
What’s Copied: Metadata only
Sandbox Templates: Not available

Developer Pro Sandbox 1 day (Refresh Interval),
Storage Limit: Data storage: 1 GB, File storage: 1 GB
What’s Copied: Metadata only
Sandbox Templates: Not available

Partial Copy Sandbox 5 days (Refresh Interval)
Storage Limit: Data storage: 5 GB, File storage: Same as your production org
What’s Copied: Metadata and sample data
Sandbox Templates: Required

Full Sandbox 29 days (Refresh Interval)
Storage Limit: Same as your production org
What’s Copied: Metadata and all data
Sandbox Templates: Available

Note: Entities defined as metadata types aren’t counted as part of storage allocations in sandboxes.

Licenses:
Professional Edition - 10 (Developer Sandbox), NA(Partial Copy)
Enterprise Edition - 25 (Developer Sandbox), 1(Partial Copy)
Unlimited Edition - 100 (Developer Sandbox), 5(Developer Pro), 1(Partial Copy), 1(Full Sandbox)
Performance Edition - 100 (Developer Sandbox), (Developer Pro), 1(Partial Copy), 1(Full Sandbox)

54
Q

Create or Edit Sandbox Templates

A

Sandbox templates control which data is copied into a Partial Copy or Full sandbox.

Sandbox templates allow you to pick specific objects and data to copy to your Full or Partial Copy sandbox to control the size and content of each sandbox. Sandbox templates are only available for use with Full or Partial Copy sandboxes.

When you create a sandbox template, you select the object data (standard and custom) to copy during the creation or refresh of a sandbox.

The sandbox template editor understands the relationships that are defined in your Salesforce org object schema. Some objects are included even before you’ve selected anything because they’re required in any org. As you select objects to copy, the editor ensures that the associated required objects are added. To see which related objects are required by an object, select it in the Object table. Required objects are displayed in the Required Objects column.

As you change the schema of the objects in your org, Salesforce updates the template by adding or subtracting related required objects. For example, if Object A is a master of Object B, and you add Object B to a template, Salesforce requires Object A in the template and adds Object A.

  1. From Setup, enter Sandboxes in the Quick Find box, select Sandboxes, then click the Sandbox Templates tab.
  2. Click New Sandbox Template or click Edit next to an existing template you want to modify.
  3. Enter a name and description for the sandbox template.
  4. To add objects to the template, select the checkbox for each object you want from the available Objects list.
  5. The Object Details section shows you the objects to be added automatically with the one you’ve selected.
  6. To remove objects from the template, deselect the checkbox for the object in the available Objects list.
    7.If you remove an object you previously selected, dependent objects you didn’t explicitly select are removed. If you attempt to remove an object with dependent objects, you receive a warning requesting a confirmation of the removal. After you confirm your choice, those objects are also removed.
    Click Save.
55
Q

Sandbox: Servers and IDs

A

Sandbox and production orgs have unique org IDs. The sandbox copy engine creates an org as part of each creation and refresh request.

The org ID of the sandbox changes each time it’s refreshed. In any place where a production org ID or a sandbox org ID is used, such as text values and metadata, Salesforce inserts the new sandbox org ID value.
To find the ID of the org that you’re logged in to, from Setup, enter Company Information in the Quick Find box, then select Company Information. A script or process, such as a test script or Web-to-Lead, that depends on a “hard-coded” org ID must use the current ID for the sandbox. When you deploy your changes to a production org, update the scripts or processes with the production org ID.

Salesforce creates sandbox orgs on several instances. When a sandbox is created or refreshed, Salesforce selects an instance for your sandbox. Sometimes, sandboxes appear on different instances and have different URLs.
When data is copied to a sandbox, object IDs for records are copied. Object IDs are unique identifiers for all objects—the same as the ID Field Type in the developer API. After being copied, however, object IDs don’t synchronize between the production org and sandbox. The sandbox and its corresponding production org act as independent orgs. Object data (and corresponding object IDs) that are created in the production org after the sandbox is created or refreshed don’t synchronize into the sandbox. The sandbox has the same behavior—new objects that are created in the sandbox aren’t synchronized back to the production org.

56
Q

Sandbox: Users and Contacts

A

User information is included in a sandbox copy or refresh for all sandbox types.
Because all Salesforce usernames must be unique and reference a single org, usernames are modified to ensure uniqueness as they are copied.
For each username, the copy process does the following.

First, the sandbox name is appended to the username. For example, the username user@acme.com for a sandbox named test becomes user@acme.com.test.
If the resulting username is not unique, a second modification is performed in which some characters and digits are prepended to the modified username. This second modification results in a username such as 00x7Vquser@acme.com.test.
When you log in with the modified username, you log in to the corresponding sandbox.
The copy process doesn’t copy Contact data to Developer or Developer Pro sandboxes. Therefore, Customer Portal users aren’t copied. However, the copy process does copy the Customer Portal licenses, so you can create Customer Portal users in Developer or Developer Pro sandboxes.
When you create or refresh a sandbox, user email addresses are modified so that production users don’t receive automatically generated email messages from the sandbox. User email addresses are appended with .invalid.

57
Q

Deployment Connections for Change Sets

A

A deployment connection is required between two Salesforce orgs to send change sets from one org to another. You can’t create deployment connections between arbitrary orgs. Instead, you create connections between all orgs affiliated with a production org. For example, if you have a production org and two sandboxes, a deployment connection is created between production and each sandbox. Also, a deployment connection is created between the two sandboxes.

A deployment connection alone doesn’t enable change sets to be sent between orgs. Each org must be authorized to send and receive change sets. This added level of security enforces code promotion paths and keeps orgs’ setup metadata from being overwritten by mistake.

For example, the following figure illustrates one possible migration path for a production org (Prod) and two sandboxes (Dev and Test). In this example, the production org can only receive changes that have been fully tested, so only the Test sandbox is authorized to upload change sets to production. To synchronize development projects with the production org, the Prod org can send change sets to the Dev sandbox, but not to the Test sandbox. Finally, because the features in development need iterative testing, Dev and Test sandboxes should be able to send change sets back and forth.

58
Q

Authorize a Deployment Connection

A

Authorize inbound changes so that another Salesforce org can send change sets to the org you are logged into.

From Setup, enter Deployment in the Quick Find box, then select Deployment Settings, and then click Continue.
Click Edit next to the org you want to authorize.
Select Allow Inbound Changes.
Click Save.

59
Q

Deployment: Change Sets

A

Use change sets to send customizations from one Salesforce org to another. For example, you can create and test a new object in a sandbox org, then send it to your production org using a change set. Change sets can contain only modifications you can make through the Setup menu. For example, you can’t use a change set to upload a list of contact records. Change sets contain information about the org. They don’t contain data, such as records.
When you want to send customizations from your current org to another org, create an outbound change set. After you send the change set, the receiving org sees it as an inbound change set.

Sending a change set between two orgs requires a deployment connection. Change sets can only be sent between orgs that are affiliated with a production org. For example, a production org and a sandbox, or two sandboxes created from the same org can send or receive change sets.

60
Q

Deployment: Permission Sets and Profile Settings in Change Sets

A

Developers can use permission sets or profile settings to specify permissions and other access settings in a change set. When deciding whether to use permission sets, profile settings, or a combination of both, consider the similarities and differences.
In API version 40.0 and later, when you deploy the output of a retrieval to another org, the metadata in the deployment replaces the target org metadata. In API version 39.0 and earlier, when you deploy your retrieved permission set output to another org, the deployment contents are merged with your current org data

For example:

In API version 40.0 and later, if your permission set contains the Manage Roles user permission and you deploy a metadata file without this user permission, Manage Roles is disabled in the target org. Or, let’s say you have a permission set with edit access to fields in an object. If the change set fails to include these fields, the permissions are still carried over to the target org and these changes are deployed.
In API version 39.0 and earlier, if you deploy a metadata file without this user permission, Manage Roles remains enabled.
Keep in mind that by default, change set deploys enable dependencies. For example, if your change set contains a custom profile with Lead Conversion enabled, Lead object permissions are enabled.

For Visualforce page access and Apex class access, always include supporting components in the change set.

61
Q

Deployment: Restrictions for Approval Processes in Change Sets

A

Understand these restrictions before you include approval processes in change sets.

If the approval page fields include any custom fields on standard objects, manually add those custom fields to outbound change sets. The View/Add Dependencies option for selecting change set components don’t include these fields.
If the approval process references any post templates that contain custom fields, resave those post templates in the originating organization before adding them to the change set. From Setup, enter Post Templates in the Quick Find box, then select Post Templates. For each post template, click Edit and then Save.
Change sets don’t include the order of active approval processes from the source org. Sometimes you must reorder the approval processes in the destination org after deployment.
If you change the Unique Name of an approval process that was previously included in a change set and deployed in another organization, and you resend the approval process via a change set, a new approval process is created upon deployment in the other organization. The previously deployed approval process isn’t modified.

62
Q

Deployment: Change Sets Implementation Tips

A

Authorization required to upload changes
Before you can deploy a change set from one org to another, an administrator in the target org must authorize uploads across the deployment connection between the two orgs.

Deployment Connections list displays all connections
The Deployment Connections list is automatically populated with your production org and all sandboxes. It is possible to deploy between any of these orgs, but no other orgs.

Change set connections unavailable during maintenance
Authorizing deployment connections and uploading pages require information from the production org, and are unavailable when production is undergoing maintenance. During this time, you can construct outbound change sets but not upload them.

Sandboxes must be available
If an org has no sandboxes provisioned, the user could see an Insufficient Privileges error on the Deployment Connections page.

Deployment doesn’t automatically restart
If an error occurs during change set validation or deployment, you must manually restart the process. Be sure that your org is not locked, undergoing maintenance, or otherwise inaccessible.

Deployment is a one-way transaction
A change set is deployed in a single transaction. If the deployment is unable to complete for any reason, the entire transaction is rolled back. After a deployment completes successfully, all changes are committed to your org and the deployment can’t be rolled back.

Deployments maintain user references
If a component in a change set refers to a specific user, such as recipients of workflow email notifications or dashboard running users, then during deployment the system attempts to locate a matching user in the destination org by comparing usernames.

When you copy data to a sandbox, the fields containing usernames from the production org are altered to include the sandbox name. For example, in a sandbox named test, the username user@acme.com becomes user@acme.com.test. During a deployment using change sets, the .test in the username is ignored. This process transfers a user added to a component in one sandbox to other sandboxes or production orgs.

Change sets with many dependent components
Opening a change set in Salesforce can take several minutes if it contains a component with many dependencies or if a component’s parent has many dependencies. The delay is because Salesforce checks component dependencies before displaying the change set page. An example of a component with many dependencies is a custom field that belongs to a custom object with 2,500 dependent components.

Action overrides in change sets
An action override is pulled into a change set if the override is associated with a custom object or app that is included in the change set.

Because you can’t include standard objects in a change set, you can’t use a change set to deploy an action override associated with a standard object.

63
Q

Change Sets Best Practices

A

Deploy all dependent components
Make sure each outbound change set contains all interdependent components that don’t exist in the target org. If you try to deploy a component that refers to another component missing from the target org and from the change set, the deployment fails.

Change sets give you fine-grained control over what you deploy. For example, you can migrate custom fields individually. To deploy a custom object and all of its fields, you must add the custom object and every field to the change set; adding just the custom object to the change set won’t cause deployment to fail, but results in an empty custom object.

Add permissions and access settings to outbound change sets
Adding profiles or permission sets to outbound change sets allows administrators to migrate permissions for users so they can access the new functionality. There are significant differences between permission sets and profile settings in change sets.

Clone a change set to add dependent components to an uploaded change set
After you upload a change set, you can’t change its contents. If you need to add dependent components to a change set you already uploaded, clone the change set, add the dependent components, and then upload it again.

Use distinct names for global publisher layouts and Outlook publisher layouts
When you add page layouts to an outbound change set, the type for global publisher layouts and Outlook publisher layouts isn’t displayed. Make sure that you provide unique names for your global publisher layouts and Outlook publisher layouts so that you can differentiate them in an outbound change set.

Plan deployments around maintenance schedule
Plan your deployment activities around the maintenance schedule for both your production and sandbox orgs. Some features require information from your production org when accessed from a sandbox. In addition, the originating org is locked while validating an outbound change set, and the target org is locked while deploying an inbound change set. (When change sets lock an org, you can still read and write data to the org, but you can’t make any setup changes that would modify the metadata.)

Validate change sets before deployment
You can perform a test deployment of an inbound change set to view the success or failure messages that would occur with an actual deployment. This is a good idea if you are planning a deployment on a schedule (for example during low-use hours) and want to determine if the deployment will succeed ahead of time. However, you don’t need to perform a test deployment every time you deploy, as this process takes time to complete and the org is locked for the duration. (You can still read and write data to the org, but you can’t make any setup changes that would modify the metadata.) To test deploy an inbound change set, click its name and then click Validate.

View component details
You can view the XML representation of a component after you upload an outbound change set or before you deploy an inbound change set.

Limit change sets to 10,000 files
Change sets are limited to 10,000 files. If your change set exceeds this limit, you can create separate change sets for email templates, dashboards, and reports. These components are often the most numerous and have fewer dependencies.

Delete or rename components using the Web interface
You can’t use change sets to delete or rename components. To delete components, use the Web interface on the target org. To rename a component, first delete the component on the target org and then upload the new component in a change set.

Editing the sharing settings for objects in a master-detail relationship, such as changing org-wide defaults from Controlled by Parent to Public Read/Write, is considered deleting a component.

Consider possible delays in deployment time when a change set includes field type changes
If a change set includes changes to custom field types, the deployment time might be delayed by an extended period of time because custom field type changes might require changes in a large number of records. To avoid long delays in deployment, an alternative is to apply the field type change manually after the change set is deployed.

Plan for tests to run in the target org
When a change set is deployed to a production org, all local Apex tests in that org are run by default if you’re deploying any Apex classes or triggers. If the target org is a sandbox, however, tests aren’t automatically run.

64
Q

View Inbound Change Sets

A

The Inbound Change Sets page lists change sets awaiting deployment, as well as the history of deployed change sets.

To view inbound change sets, from Setup, enter Inbound Change Sets in the Quick Find box.
Select Inbound Change Sets.
Inbound change sets are permanently deleted six months after the change set is uploaded.

65
Q

Monitor Deployments of Change Sets

A

Track the status of deployments that are in progress in the Deployment Status page.

From Setup, enter Deployment Status in the Quick Find box.
Select Deployment Status
The Deployment Status page also shows completed deployments.

Alternatively, you can check completed deployments on the Change Set Detail page. To access this page from Setup, enter Inbound Change Sets in the Quick Find box, select Inbound Change Sets, and then click the name of a deployed change set. Deployments for the change set are listed under the Deployment History section.

66
Q

Select Components for an Outbound Change Set

A

You typically use an outbound change set for customizations created and tested in a sandbox and that are then sent to a production org.

To select the components in an outbound change set:

From Setup, enter Outbound Change Sets in the Quick Find box, then select Outbound Change Sets.
In the Change Sets list, click the name of a change set, or create a new one.
Click Add to add components.
Choose the type of component and the components you want to add, and then click Add to Change Set.
Click Add Profiles to add profile settings to the change set. You can’t add profile settings to a change set in Professional Edition.
Optionally, click View/Add Dependencies to add dependent components. Dependent components rely on the existence of other components. Unless you’re certain that the dependent components exist in every org this change set will be deployed to, add dependent components to the change set.

For example, Apex Class A has a dependency on Class B and Object B. Class B has a dependency on Class C and Object C. When Apex Class A is added to a change set, these components are listed as dependencies.

Class A
Class B
Class C
Object B
Object C

While Class C doesn’t have a direct dependency on Class A, Class C and Object C are required.

67
Q

Upload an Outbound Change Set

A

When you’ve assembled the components in a change set, you can upload it to another Salesforce org. After you upload a change set, you can’t edit it or recall it.

From Setup, enter Outbound Change Sets in the Quick Find box, then select Outbound Change Sets.
Click Upload next to the change set you want to upload. To review the change set before uploading it, click the name of the change set to view its detail page. When ready, click Upload.
If the change set doesn’t contain any components, the Upload link isn’t available.

Select the org you want to send the change set to.
Click Upload.
Outbound change sets expire six months after upload. Change sets are permanently deleted when they expire.

68
Q

Metadata API Edit Access

A

To use Metadata API, a user must have these things.

One of these editions: Enterprise, Unlimited, or Developer
Either the Modify Metadata Through Metadata API Functions OR Modify All Data permission
Permission that enables use of the feature supported by the metadata that they want to modify
Permission that enables their deployment tool, such as Salesforce CLI, change sets, or the Ant Migration Tool
With the Modify Metadata Through Metadata API Functions permission, a user can access and edit metadata via Metadata API as long as the user has any additional permission needed to access certain metadata types. This additional permission information is listed in the Metadata API Developer Guide for each metadata type. With the Modify All Data permission, a user can access and edit all data.

The Modify Metadata Through Metadata API Functions permission doesn’t affect direct customization of metadata using Setup UI pages because those pages don’t use Metadata API for updates.

Some metadata, such as Apex, executes in system context, so be careful how you delegate the Modify Metadata Through Metadata API Functions permission. The Modify Metadata Through Metadata API Functions permission allows deployment of Apex metadata, but it doesn’t allow certain Apex development and debugging features that still require the Modify All Data permission.

The Modify Metadata Through Metadata API Functions permission is enabled automatically when either the Deploy Change Sets OR Author Apex permission is selected.

When the Manage Prompts user permission and the Modify Metadata Through Metadata API Functions permission are combined, users can manage In-App Guidance in Lightning Experience.

69
Q

Monitor Deployments

A

Setup > You can monitor deployments that are in progress, check which deployments are waiting for execution, and view the results of completed deployments on the Deployment Status page.
This page lists all deployments—change sets, Metadata API-based deployments, including deployments started from the Salesforce Extensions for Visual Studio Code and the Ant Migration Tool, and package installations.
After all components have been deployed without errors, Apex tests start executing, if required or enabled. A second chart shows how many Apex tests have run out of the total number of tests and the number of errors returned. In addition, the chart shows the name of the currently running test.
Deployments that have completed successfully or have partially succeeded are listed in the Succeeded section. Only deployments to a non-production org can partially succeed. These are deployments that have the rollbackOnError field set to false in the deployment options and have errors in a subset of components. In a partially succeeded deployment, the failed components aren’t committed and the remaining components are committed to the org.

70
Q

Quick Deployments

A

As part of a deployment, all Apex tests are run in production. If the production org contains many Apex tests, executing the tests can be time consuming and can delay your deployment. To reduce deployment time to production, you can perform a quick deployment by skipping the execution of tests. Quick deployments are available for change sets and Metadata API components when the following requirements are met.

The components have been validated successfully for the target environment within the last 10 days.
As part of the validation, Apex tests in the target org have passed.
Code coverage requirements are met.
If all tests in the org or all local tests are run, overall code coverage is at least 75%, and Apex triggers have some coverage.
If specific tests are run with the Run specified tests test level, each class and trigger that was deployed is covered by at least 75% individually.
A validation is a deployment that’s used only to check the results of deploying components and doesn’t save any components in the org. A validation enables you to view the success or failure messages that you would receive with an actual deployment. You can validate change sets or metadata components through the API or the Ant Migration Tool.

To learn how to validate a change set, see Validate a Change Set in the Salesforce Help.

To validate components with the Ant Migration Tool, set the checkOnly option to true in the deploy target. See Deploying Changes to a Salesforce Organization in the Ant Migration Tool Guide.