Tuesday 25 August 2015

How to insert User with UserRole in testclass in Salesforce

         Hope many of Salesforce techies came across to inserting user record in test class. The below code will help your to solve your problem on inserting user with role. I would like to suggest create a separate util class for user creation like below. You can call it where ever you need in test class.

        Generally if you insert same user record details in more than one test method, then you will receive an exception as below,

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>Another user has already selected this username.

To avoid such issue, randomly set the user name, email in your util method and create user like below,

Test Class Utility:

  1. @isTest
  2. public class TestUserUtil
  3. {
  4.     public static User createTestUser(Id roleId, Id profID, String fName, String lName)
  5.     {
  6.         String orgId = UserInfo.getOrganizationId();
  7.         String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
  8.        
  9.         Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
  10.         String uniqueName = orgId + dateString + randomInt;
  11.         User tuser = new User(  firstname = fName,
  12.                                 lastName = lName,
  13.                                 email = uniqueName + '@test' + orgId + '.org',
  14.                                 Username = uniqueName + '@test' + orgId + '.org',
  15.                                 EmailEncodingKey = 'ISO-8859-1',
  16.                                 Alias = uniqueName.substring(1823),
  17.                                 TimeZoneSidKey = 'America/Los_Angeles',
  18.                                 LocaleSidKey = 'en_US',
  19.                                 LanguageLocaleKey = 'en_US',
  20.                                 ProfileId = profId,
  21.                                 UserRoleId = roleId);
  22.         return tuser;
  23.     }
  24. }


Test class:

  1. @isTest
  2. private class TestWorkLocation
  3. {
  4.     static testMethod void positiveDataInsert()
  5.     {
  6.         Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
  7.        
  8.         UserRole ur = new UserRole(Name = 'CEO');
  9.         insert ur;
  10.         User usr = TestUserUtil.createTestUser(ur.Id, pf.Id'Test FirstName''Test LastName');
  11.        
  12.         System.runAs(usr)
  13.         {
  14.             // Do your logic here.
  15.         }
  16.     }
  17. }

How to sort more than one field/column using Comparable Interface in Salesforce

         Recently, I had a requirement to sort more than one field/column and display the result in visualforce page.

        The Sorting order should be in the following way,

                  FIRST COLUMN should be in DESCENDING order.
                  SECOND COLUMN should be in ASCENDING order. 


Wrapper Class:

  1. public class PurchaseHistoryWrapper implements Comparable
  2. {
  3.     public enum SortField{purchasedYearEnum, purchasedQtyEnum}
  4.     public static SortField SORT_FIELD = SortField.purchasedYearEnum;
  5.    
  6.     public String purchasedYear{get;set;}
  7.     public String purchasedQty{get;set;}  
  8.    
  9.     public Integer purchasedYearInt{
  10.         get{
  11.             if(purchasedYear != null){
  12.                 return Integer.valueOf(purchasedYear);
  13.             }return 0;
  14.         }set;
  15.     }
  16.    
  17.     public Integer purchasedQtyInt{
  18.         get{
  19.             if(purchasedQty != null){
  20.                 return Integer.valueOf(purchasedQty);
  21.             }return 0;
  22.         }set;
  23.     }
  24.    
  25.     public Integer compareTo(Object other) {
  26.         if(SORT_FIELD == SortField.purchasedYearEnum)
  27.             return compareToPurchasedYear(other);
  28.         else if (SORT_FIELD == SortField.purchasedQtyEnum)
  29.             return compareToPurchasedQty(other);
  30.         else
  31.             return 0;
  32.     }
  33.    
  34.     public Integer compareToPurchasedYear(Object compareTo){
  35.         PurchaseHistoryWrapper compareToModel = (PurchaseHistoryWrapper)compareTo;
  36.         // Decending Order comparison.
  37.         if(purchasedYearInt < compareToModel.purchasedYearInt)
  38.             return 1;
  39.         else if(purchasedYearInt == compareToModel.purchasedYearInt)
  40.             return 0;
  41.         else
  42.             return -1;
  43.     }
  44.    
  45.     public Integer compareToPurchasedQty(Object compareTo){
  46.         PurchaseHistoryWrapper compareToModel = (PurchaseHistoryWrapper)compareTo;
  47.         // Ascending Order comparison.
  48.         if(purchasedQtyInt > compareToModel.purchasedQtyInt)
  49.             return 1;
  50.         else if(purchasedQtyInt == compareToModel.purchasedQtyInt)
  51.             return 0;
  52.         else
  53.             return -1;
  54.     }
  55. }


Apex Class:
  
  1. Public class PurchaseHistoryController
  2. {
  3.     public List<PurchaseHistoryWrapper> purchaseList{get;set;}
  4.     public string puchaseListString;
  5.    
  6.     public PurchaseHistoryController()
  7.     {
  8.         String jsonString = '[ { "purchasedYear": "2014", "purchasedQty":"25" }, { "purchasedYear": "2015", "purchasedQty":"2" }, { "purchasedYear": "2014", "purchasedQty":"1" }, { "purchasedYear": "2015", "purchasedQty":"12" }, { "purchasedYear": "2014", "purchasedQty":"222" }, { "purchasedYear": "2015", "purchasedQty":"3" } ]';
  9.         purchaseList = (List<PurchaseHistoryWrapper>) System.JSON.deserialize(jsonString, List<PurchaseHistoryWrapper>.class);
  10.        
  11.         if(purchaseList != null && purchaseList.size() > 0)
  12.         {
  13.             purchaseList.sort();
  14.             puchaseListString = multiSort(purchaseList);
  15.             purchaseList = (List<PurchaseHistoryWrapper>) System.JSON.deserialize(puchaseListString, List<PurchaseHistoryWrapper>.class);
  16.         }
  17.     }
  18.    
  19.     public String multiSort(List<PurchaseHistoryWrapper> purchaseList)
  20.     {
  21.         List<PurchaseHistoryWrapper> tempPurchaseList = new List<PurchaseHistoryWrapper>();
  22.         Map<String,List<PurchaseHistoryWrapper>> phMap = new Map<String,List<PurchaseHistoryWrapper>>();
  23.         for(PurchaseHistoryWrapper currPurchase: purchaseList)
  24.         {
  25.             if(phMap.containsKey(currPurchase.purchasedYear))
  26.             {
  27.                 phMap.get(currPurchase.purchasedYear).add(currPurchase);
  28.             }
  29.             else
  30.             {
  31.                 phMap.put(currPurchase.purchasedYear,new List<PurchaseHistoryWrapper>{currPurchase});
  32.             }
  33.         }
  34.         for(String key : phMap.keySet())
  35.         {
  36.             List<PurchaseHistoryWrapper> phTemp =  phMap.get(key);
  37.             //Enum
  38.             PurchaseHistoryWrapper.SORT_FIELD = PurchaseHistoryWrapper.SortField.purchasedQtyEnum;
  39.             phTemp.sort();
  40.             tempPurchaseList.addAll(phTemp);  
  41.         }
  42.         return json.serialize(tempPurchaseList);
  43.     }
  44. }

Visualforce Page:

  1. <apex:page controller="PurchaseHistoryController">
  2.     <apex:form >
  3.         <apex:pageBlock >
  4.             <apex:pageBlockTable value="{!purchaseList}" var="pl">
  5.                 <apex:column headerValue="Purchased Year" value="{!pl.purchasedYear}"/>
  6.                 <apex:column headerValue="Number of Quantity" value="{!pl.purchasedQty}"/>
  7.             </apex:pageBlockTable>
  8.         </apex:pageBlock>
  9.     </apex:form>
  10. </apex:page>

Output Page:


Thursday 20 August 2015

How to write a test class for the SOSL Query in Salesforce

             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.

Apex Class:

  1. public class SOSLController
  2. {
  3.     public static void findMatchingData(String str)
  4.     {
  5.         List<List<Sobject>> searchList = [FIND :str RETURNING Account(Id, Name), Lead];       
  6.         List<Account> accounts = ((List<Account>)searchList[0]);
  7.         if(accounts.size() > 0)
  8.         {
  9.             for(Account currAcc : accounts)
  10.             {
  11.                 // do your logic.
  12.             }
  13.         }
  14.     }
  15. }

Test Class:

  1. @isTest
  2. private class TestSOSLController
  3. {
  4.     static testMethod void insertAccount()
  5.     {
  6.         Account acc = new Account();
  7.         acc.Name = 'Test Account';
  8.         insert acc;
  9.        
  10.         Id [] fixedSearchResults= new Id[1];
  11.         fixedSearchResults[0] = acc.Id;
  12.         Test.setFixedSearchResults(fixedSearchResults);
  13.         SOSLController.findMatchingData('Test');
  14.     }
  15. }


Step 1: Create a record that you want to return in a search result.
Step 2: Create a list and assign the inserted id. 
Step 3: Use standard method Test.setFixedSearchResults and pass the above ID list.
Step 4: Call your apex method to test your functionality. 


Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...