Category: test class

Spring’20 Brings Improved Code Coverage Result for Apex Test Class

 Writing test classes to cover both positive, negative, and bulkified scenarios are always the best practices that each developer should follow. While writing test classes, our approach should be to cover as much as code and all the scenarios. There is a restriction from Salesforce that if there is not enough coverage (75%) for the code, then Salesforce will not allow you to deploy your code to production.So identifying the code coverage is very important. Now there are multiple ways we can get to know the code coverage like – Setup menu, Developer Console, SOQL Query, Salesforce CLI, or Salesforce extension in Visual Studio Code. With so many options there comes the difficulties. Each option presents the code coverage in a different way and more importantly, each option calculates code coverage in a different way. This always creates confusion. For example, when a developer writes the test class and executes that from CLI, it provides the code coverage, let’s say 90%, which should be good enough to deploy the code into Production. But while deployment, the code coverage came down to 50%, and thus deployment stops. The reason for this drop in code coverage is that while deploying code coverage is calculated at the org level i.e. percentage of coverage for that class across the org.To solve this problem, Salesforce comes up with the Enhanced Code Coverage option. With...

Read More

How to handle DUPLICATE_USERNAME error while performing deployment

Recently, while doing deployment through change set, I faced an issue -System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.Another user has already selected this username.Please select another.: [Username]”The username used in test classes were definitely unique, but still my test classes were failing with the below error message. After spending some quite amount of time, I have understood the problem. So thought of putting this in my blog hoping that it may help someone in future.So here it goes -Error message -System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.Another user has already selected this username.Please select another.: [Username]”Reason -Usernames are always shared across instances, but not across environments. It means if a user is having username as in any sandbox, then this same username you can’t use in any other sandbox instances (CS*), but you can user the same username in production sandboxes (NA*, EU*, AP*). Uniqueness is always checked during deployment when tests are run. So an insert from test class will also fail if the username is already registered in another org in the same environments. So we need to make sure the uniqueness in maintained in test classes.Resolution -To be 100% sure that the username used in test classes are unique, you should follow the below approach to define the username –    String orgId =...

Read More

Salesforce Summer 15 New Feature || New way to calculate code coverage for multiline statements

In Summer 15 release, Salesforce changed the way to calculate code coverage for multiline statements. As a developer, you feel good in some situation and bad in some situations. In this post, I will explain both the situations.Let me first explain the change -If a single statement is broken into multiple lines, then each line will be considered now while calculating the code coverage. To be more precise, each line that contains an expression will be considered while calculating code coverage. Before Summer 15 release, multiline was considered as a single line.To explain more, I will start with a simple code snippet.Situation 1 – Happy Situation:Consider the below code snippet.Now say for example, you have written unit test methods for the methods calculateDistanceBetweenAB(), calculateDistanceBetweenBC(), calculateDistanceBetweenCD() and calculateDistanceBetweenDA().You have also written test methods to cover line# 8,9 and 10. The only line which is not covered/tested is line# 11.Now before Summer 15 release, the way in which code overage was calculated -Total number of lines = 4 (line # 3,8,9 and 11)Total number of lines covered = 3 (line # 3,8 and 9)So the code coverage = 3/4 i.e. 75%But after Summer 15 release, the way in which code overage will be calculated -Total number of lines = 7 (line # 3,4,5,6,8,9 and 11)Total number of lines covered = 6 (line # 3,4,5,6,8 and 9)So the code coverage = 6/7...

Read More

Spring ’15 – New Feature Added – @testSetup

One of the very interesting feature added in Spring ’15 is @testSetup. In this post I will try to explain with example more about the feature. Below is what you will get from release note about @testSetup.Now let’s check with example -Below is the class/methods for which we need to write test methods – public class AccountHelper { public List<Account> getAllAccounts(){ List<Account> allAccounts = [Select Id from Account]; return allAccounts; } public Integer getEmployeeCountFrom(String accountNumber){ Account fetchedAccount = [Select Id, NumberOfEmployees from Account where AccountNumber = :accountNumber LIMIT 1]; return fetchedAccount.NumberOfEmployees; } public List<Case> getAllCases(Id accountId){ return [select ID from Case where AccountId = :accountId]; } public void updateEmployeeCountFor(String accountNumber, Integer newEmployeeCount){ Account fetchedAccount = [Select Id, NumberOfEmployees from Account where AccountNumber = :accountNumber LIMIT 1]; fetchedAccount.NumberOfEmployees = newEmployeeCount; update fetchedAccount; }}Previously we used to write test classes like below -@isTestpublic class AccountHelperTest { static testMethod void testGetAllAccounts(){ List<Account> accounts = new List<Account>(); for(Integer i=0;i < 100;i++){ accounts.add(new Account(Name = ‘Universal Container’)); } insert accounts; Test.startTest(); AccountHelper accountHelper = new AccountHelper(); List<Account> allAccounts = accountHelper.getAllAccounts(); Test.stopTest(); System.assertEquals(100, allAccounts.size()); } static testMethod void testGetEmployeeCountFrom(){ Account anAccount = new Account(); anAccount.Name = ‘Universal Container’; anAccount.AccountNumber = ‘TEST’; anAccount.NumberOfEmployees = 100; insert anAccount; Test.startTest(); AccountHelper accountHelper = new AccountHelper(); Integer numberOfEmployees = accountHelper.getEmployeeCountFrom(‘TEST’); Test.stopTest(); System.assertEquals(100, numberOfEmployees); } static testMethod void testGetAllCases(){ //Create the account first Account anAccount = new Account(); anAccount.Name = ‘Universal Container’; insert anAccount;...

Read More

JSON Parsing with Apex in Salesforce – Part II

This post is in continuation of my previous post regarding JSON Parsing.In this post, what I am going to share is-How to parse a little more complex JSON containing array. Once the JSON data is parsed, how to display the same information in Visual Force Page.Check the below link to understand what I am trying to achieve at the end of this post let’s start with creating the Visual Force Page<apex:page controller=”StudentDetailController”> <apex:form > <apex:pageBlock Title=”JSON Parser Example”> <apex:commandButton value=”Parse JSON Data” action=”{!parseJSONData}” reRender=”studentData” /> </apex:pageBlock> <br /> <apex:pageBlock id=”studentData”> First Name: <apex:inputText value=”{!firstName}” /> Last Name: <apex:inputText value=”{!lastName}” /> <br/> <apex:pageBlockSection title=”Language Known:” collapsible=”false”> <apex:selectList value=”{!selectedLanguage}” multiselect=”false” size=”1″> <apex:selectOptions value=”{!languageOptions}”/> </apex:selectList> </apex:pageBlockSection> </apex:pageBlock> </apex:form></apex:page>Now the controller-public class StudentDetailController{ public String firstName{get;set;} public String lastName{get;set;} public String selectedLanguage{get;set;} private StudentDetailWrapper m; public List<SelectOption> languageOptions; public void parseJSONData(){ m = new ParseStudentData().parseData(); doAllInitialization(); } public void parseJSONData(String jsonMessage){ m = new ParseStudentData().parseData(jsonMessage); doAllInitialization(); } public List<SelectOption> getLanguageOptions(){ if(null == languageOptions){ languageOptions = new List<SelectOption>(); } return languageOptions; } private void doAllInitialization(){ initializeStudentName(); initializeLanguageOptions(m.language); } private void initializeStudentName(){ this.firstName = m.firstName; this.lastName = m.lastName; } private void initializeLanguageOptions(List<String> language){ languageOptions = new List<SelectOption>(); for(String aLanguage : language){ languageOptions.add(new SelectOption(aLanguage, aLanguage)); } }}Now the class which will do the JSON Parsing-public class ParseStudentData { private StudentDetailWrapper m; public StudentDetailWrapper parseData(String jsonMessage){ return doParsing(jsonMessage); } public StudentDetailWrapper parseData(){ String jsonMessage = ‘{“firstName” : “Sudipta”,...

Read More