Author Archives: Biswajeet

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

Difference between Process Builder and Workflow in Salesforce

Process builder allows you to do the below actions:

  • Create a new record.
  • Update any related record.
  • Quick action to create a record, update a record, or log a call.
  • Launch a flow.
  • Send an email
  • Post to Chatter.
  • Submit for approval
  • Call apex methods
  • But the process builder doesn’t support outbound messages.

Workflows can only handle four types of actions:

  • Create Task.
  • Update Field.
  • Email Alert.
  • Outbound Message.

Best Practice for Test Classes in Salesforce

  • To deploy to production at-least 75% code coverage is required, But your focus shouldn’t be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.
  • Test class must start with @isTest annotation if class version is more than 25.
  • @isTest annotation with test method  is equivalent to testMethod keyword.
  • Test class and method default access is private ,no need to add access specifier.
  • Classes with @isTest annotation can’t be a interface or enum.
  • Test method code can’t be invoked by non test request.
  • Stating with salesforce API 28.0 test method can not reside inside non test classes.
  • Always use @testSetup method dedicated to create test records for that class. This is newly added annotation and very powerful.
  • If possible Don’t use seeAllData=true, Create your Own Test Data. SeeAllData=true will not work for API 23 version earlier.
  • User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true).
  • @TestVisible annotation can be used to access private members and methods inside Test Class. Now we don’t need to compromise with access specifiers for sake of code coverage.
  • Test method and test classes are not counted as a part of code limit.
  • Test method takes no argument, commit no data to database, send no email, flagged with testMethod keyword.
  • Use Test.startTest() to reset Governor limits in Test methods.
  • If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest() to make sure that operation is completed.
  • Use System.runAs() method to enforce OWD and Profile related testings. This is very important from Security point of View.
  • System.runAs() will not enforce user permission or field level permission.
  • Use As much as Assertions like System.AssertEquals or System.AssertNotEquals.
  • Always test Batch Capabilities of your code by passing 20 to 100 records.
  • Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
  • Please use call out mock to test web-service call out .
  • System.debug statement are not counted as a part of apex code limit.
  • We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
  • Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface in Salesforce

Callout Class:

public class CalloutClass {
    
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.salesforce.com/foo/bar');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}

Mock Http Response Generator Class:

@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    
    global HTTPResponse respond(HTTPRequest req) {
        
        System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}

Callout Test Class:

@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
         
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

Create Remote Site Settings Using Apex (Metadata API)

Sample Code:

//Metadata Service
MetadataService.MetadataPort service = new MetadataService.MetadataPort();
ServiceCreation.SessionHeader = new MetadataService.SessionHeader_element();
ServiceCreation.SessionHeader.sessionId = UserInfo.getSessionId();

//Metadata for remote site settings
MetadataService.RemoteSiteSetting remoteSiteSettings = new MetadataService.RemoteSiteSetting();
remoteSiteSettings.fullName = 'Google';
remoteSiteSettings.url = 'https://www.google.com';
remoteSiteSettings.description = 'Remote site settings created from apex';
remoteSiteSettings.isActive = true;
remoteSiteSettings.disableProtocolSecurity = false;
MetadataService.SaveResult[] results = service.createMetadata(new List<MetadataService.Metadata> { remoteSiteSettings });

for(MetadataService.SaveResult sr : results){
    if(result.success){
        //Success
        system.debug('Sucess - ' + result);
    }else{
        //Failed
        system.debug('Failed - '+ result.errors[0].message);
    }
}

Note: You need to import all the metadata classes from Metadata WSDL to get this working.

Limitations of Salesforce ChangeSets

ChangeSets is one of the tools that Salesforce provides for developers to migrating metadata and configuration changes between environments. There are some limitation in ChangeSets. Here are the limitations of ChangeSets, that is why developers need alternative deployment solutions to ChangeSets.

  • You cannot deploy all types of metadata components in one shot. For example, if you are deploying custom settings and a Visualforce page which leverages those custom settings, we cannot deploy all those components at once. Developers would first need to deploy custom settings, and then create a Changeset for deploying Visualforce page.
  • Code merging from various organizations into a single deployment unit is not feasible by using Salesforce ChangeSets. Salesforce recommends that each developer work in their own developer organization.
  • You need to create Salesforce ChangeSets over and over again. For example, if a developer needs to deploy the code from Dev to QA to UAT organizations, they would have to create the ChangeSets twice to move across these two organizations.
  • There is no way to deploy successful components and ignore the failed components. Salesforce ChangeSets either deploy all the components or rollback all the components on any failure.
  • Salesforce ChangeSets do not support all types of metadata components.
  • It’s not feasible to integrate Salesforce ChangeSets with any version control system.
  • Stop overwriting changes from other developers, because metadata components are not versioned, we often overwrite each other’s changes. For example, a developer can deploy the latest version of a component. Subsequently, another developer can redeploy the “older version” of the component which was not changed.
  • For any deployment, developer need to upload ChangeSets and deploy them to the target organization. This greatly increases the deployment time.
  • Any developer can make any modification to another organization if they have permissions to make changes to it. The auditor cannot track who made the changes to the organization.