-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
31Questions
-
39Replies
System.DmlException: Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, bad value for restricted picklist field: Contract Path: [RelationshipType__c]
How do I solve this error? If I select other picklist values form the list it gives me asserts error and if I select the mostly used values it give me the error above. I have googled the error and lots of people says uncheck the Restricted picklist checkbox but I will need that box checked in production so I was looking for some solution where I get to keep the box checked and not have the errors.
@isTest public with sharing class CloneListTest { static testmethod void testCloneListControllerOne() { List<Account> allAccounts = new List<Account>(); //Create client Account Account clientAccount = new Account(); clientAccount.Name = 'Client Account'; //Create partner Accounts Account partnerAccountOne = new Account(); partnerAccountOne.Name = 'Partner Account 1'; Account partnerAccountTwo = new Account(); partnerAccountTwo.Name = 'Partner Account 2'; allAccounts.add(clientAccount); allAccounts.add(partnerAccountOne); allAccounts.add(partnerAccountTwo); insert allAccounts; Id clientAccountId = [SELECT Id from Account WHERE Id = :clientAccount.Id].Id; //Create parent Client Overview record (this will be deep cloned) Contract testClientOverview = new Contract(); testClientOverview.AccountId = clientAccountId; testClientOverview.name = 'Client Overview Record'; testClientOverview.RecordTypeId = System.Label.Program_Agreement_Record_Type; insert testClientOverview; Id clientOverviewId = [SELECT ID FROM Contract WHERE Id = :testClientOverview.id].Id; List<Contract> programOverviews = new List<Contract>(); //Insert related Program Overview Records Contract testProgramOverviewOne = new Contract(); testProgramOverviewOne.name = 'Program Overview Record 1'; testProgramOverviewOne.AccountId = clientAccountId; testProgramOverviewOne.Program_Name__c = 'Diabetes'; testProgramOverviewOne.Client_Overview__c = clientOverviewId; testProgramOverviewOne.RecordTypeId = System.Label.Program_Schedule_Record_Type; Contract testProgramOverviewTwo = new Contract(); testProgramOverviewTwo.name = 'Client Overview Record'; testProgramOverviewTwo.AccountId = clientAccountId; testProgramOverviewTwo.Program_Name__c = 'Hypertension'; testProgramOverviewTwo.Client_Overview__c = clientOverviewId; testProgramOverviewTwo.RecordTypeId = System.Label.Program_Schedule_Record_Type; programOverviews.add(testProgramOverviewOne); programOverviews.add(testProgramOverviewTwo); insert programOverviews; //Create Contract-level Partnership Relationship records List<Relationship__c> allRelationships = new List<Relationship__c>(); Relationship__c testRelationshipOne = new Relationship__c(); testRelationshipOne.RelationshipType__C = 'Contract Path'; //Relationship Type should be "Contract Path" //testRelationshipOne.RelationshipType__C = 'Activity Tracking Devices'; //Relationship Type should be "Contract Path" testRelationshipOne.Partner_Contract_Partnership__c = [select Id FROM Account WHERE Id = :partnerAccountOne.Id].Id; testRelationshipOne.Contract_Partnership__c = clientOverviewId; allRelationships.add(testRelationshipOne); Relationship__c testRelationshipTwo = new Relationship__c(); testRelationshipTwo.RelationshipType__C = 'Billing Partner'; //Relationship Type should be "Billing Partner" //testRelationshipTwo.RelationshipType__C = 'Asthma'; //Relationship Type should be "Billing Partner" testRelationshipTwo.Partner_Contract_Partnership__c = [select Id FROM Account WHERE Id = :partnerAccountTwo.Id].Id; testRelationshipTwo.Contract_Partnership__c = clientOverviewId; allRelationships.add(testRelationshipTwo); insert allRelationships; Test.startTest(); List<List<String>> testSourceInformation = new List<List<String>>(); //Source Object Name, Child Object Name, Parent Id List<String> allInfo = new List<String>{'Contract', 'Contract, Relationship__c', string.valueof(clientOverviewId)}; testSourceInformation.add(allInfo); List<String> clonedParentId = clientOverviewServices.copyChildRecords(testSourceInformation); Test.stopTest(); Contract clonedParentRecord = [SELECT Name, Is_Cloned__c FROM Contract WHERE Id = :Id.valueOf(clonedParentId.get(0))]; System.assertEquals(TRUE, clonedParentRecord.Is_Cloned__c); System.assertEquals(2, [SELECT Id FROM Contract WHERE Client_Overview__c = :Id.valueOf(clonedParentId.get(0))].size()); System.assertEquals(2, [SELECT Id FROM Relationship__c WHERE RelationshipType__c = 'Contract Path'].size()); System.assertEquals(2, [SELECT Id FROM Relationship__c WHERE RelationshipType__c = 'Billing Partner'].size()); //System.assertNotEquals(null, clonedParentId); //System.debug(System.assertEquals(0, [select count() from Contact where AccountId =: testAccountTwo.Id]); } }
- newbiewithapex
- April 03, 2019
- Like
- 0
how to solve Attempt to de-reference a null object error?
Can someone please help me fix the "Attempt to de-reference a null object" error for this method below. I am getting error on 3rd line"testClass.updateStatusNew(null, null);"
static testMethod void testupdateStatusNew(){ TaskHandler testClass = new TaskHandler(); testClass.updateStatusNew(null, null); List<Account> acclstnew = new List<Account>(); List<Opportunity> opplstnew = new List<Opportunity>(); Set<Id> TestcbrIds = new Set<Id>(); Map<Id,CBR__c> TestcbrMap = new Map<Id,CBR__c>(); List<CBR__c> cbrtoConvertList = new List<CBR__c>(); String aggignedCBRrecId = Schema.SObjectType.CBR__c.RecordTypeInfosByName.get('Assigned CBR').RecordTypeId; Account acc = UTIL_TestDataCreation.createSingleAccount('TestAccountName', thisUser.Id); acc.Account_Class__c = 'Ship To'; testCBR.Tandem_Account_Name__c= acc.Id; testCBR.CBR_Due_Date__c = System.today(); testCBR.CBR_Assigned_By__c = thisUser.Id; testCBR.CBR_Assigned_Date__c = System.Today(); testCBR.Risk_Level__c = ''; testCBR.CBR_Owner__c = thisUser.Id; testCBR.CBR_Status__c = 'Assigned'; testCBR.RecordTypeId = null; TestcbrIds.add(testCBR.Tandem_Account_Name__c); TestcbrMap.put(testCBR.Tandem_Account_Name__c,testCBR); cbrtoConvertList.add(testCBR); Database.insert(testCBR,true); Contact conObj = UTIL_TestDataCreation.createContact('Aron','David', true); test.startTest(); testClass.updateStatusNew(TestcbrIds,TestcbrMap); test.stopTest(); }
- newbiewithapex
- February 21, 2019
- Like
- 0
Send emails test class
I have this method that send emails to event invitees on event update. I am trying to cover few missing lines but I can't seem to figure it out how. Can someone please take a look and help me out?
public static void sendEmailPostEventUpdate(Event updatedEvent){ List<EventRelation> eveRels = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :updatedEvent.Id ORDER BY Relation.Name ASC]; System.debug('eveRels' + eveRels); List<Id> leadRecptList = new List<Id>(); List<Id> userRecptList = new List<Id>(); List<Id> contactRecptList = new List<Id>(); for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } System.debug('Initiating emailSending...'); sendEmail(leadRecptList,userRecptList,contactRecptList,updatedEvent); }
- newbiewithapex
- February 21, 2019
- Like
- 0
Account Number and Division Number coverage
I have these main class and test class that I am working with. I have it at 76% and only missing 4 lines of coverage. Can someone please take a look and let me know what am I missing here to cover those 4 lines?
//MAIN CLASS public class ARStatementValidate { @AuraEnabled public static String getTandemDivisionNo(String accId) { String tandemNo; String divisionNo; String resp; System.debug(tandemNo); System.debug(divisionNo); System.debug(resp); if(isProfileNotToBeAllowed()){ return 'profileCheckFailed'; } else{ for(Account a : [SELECT Id, Tandem_Account_Number__c, Division_Number__c FROM Account WHERE Id = :accId]){ tandemNo = a.Tandem_Account_Number__c; divisionNo = a.Division_Number__c; } if(tandemNo != null && tandemNo != '' && divisionNo != null && divisionNo != ''){ resp = 'SUCCESSSS'; system.debug('-----------' + resp + '------------'); return resp; }else{ return null; } } } public static boolean isProfileNotToBeAllowed(){ SalesforceIds__c profileIds = SalesforceIds__c.getOrgDefaults(); System.debug(profileIds); return (UserInfo.getProfileId().contains(profileIds.Profile_USF_ChefStoreRep__c)); } } //TEST CLASS @isTest public class ARStatementValidateTest { private static User thisUser = [select Id, Profile.Name, Name from User where Id = : UserInfo.getUserId() limit 1]; private static User testUser = new User(); @testSetup static void createTestData() { SalesforceIds__c settings = new SalesforceIds__c(); settings.Name = 'SF Environment Settings'; settings.Profile_USF_ChefStoreRep__c = UserInfo.getProfileId(); insert settings; } Static testMethod void verifyURL(){ Account acc = UTIL_TestDataCreation.createSingleAccount('TestAccountName1', thisUser.Id); acc.Tandem_Account_Number__c='123'; acc.Division_Number__c='123'; Database.insert(acc); String finalURL = ARStatementValidate.getTandemDivisionNo(acc.id); Boolean check ; if(finalURL != null) check = true; else check = false; } Static testMethod void verifyNullURL(){ Account acc = UTIL_TestDataCreation.createSingleAccount('TestAccountName1', thisUser.Id); Database.insert(acc); String finalURL = USFoodOnlineSetupFormCntrl.getTandemAccNo(acc.id); Boolean check ; if(finalURL == null){ check = true; }else{ check = false; } } static testMethod void testElse() { Account acc = UTIL_TestDataCreation.createSingleAccount('TestAccountName1', thisUser.Id); acc.Tandem_Account_Number__c='12345'; acc.Division_Number__c='1010'; Database.insert(acc, true); Account acc1 = UTIL_TestDataCreation.createSingleAccount('TestAccountName1', thisUser.Id); acc1.Tandem_Account_Number__c='45674'; acc1.Division_Number__c=''; Database.insert(acc1, true); Test.StartTest(); Profile profileId = [SELECT Id FROM Profile WHERE Name = 'USF_TerritoryManager' LIMIT 1]; List<Account> accounts = [SELECT Id, Tandem_Account_Number__c, Division_Number__c FROM Account]; accounts.add(acc); accounts.add(acc1); User testUser = UTIL_TestDataCreation.createUser('tmtst', profileId.Id); Database.insert(testUser,true); System.runAs(testUser) { ARStatementValidate.isProfileNotToBeAllowed(); String results= ARStatementValidate.getTandemDivisionNo(String.valueOf(accounts[0].Id)); } Test.StopTest(); } }
- newbiewithapex
- February 21, 2019
- Like
- 0
How to write test class for the method that take user back?
I have method that used to go back by clicking cancel button. Can someone help me figure out test class for this method?
public pageReference back() { pageReference pf; if (ApexPages.currentPage().getParameters().get('Id') != null) { pf = new pageReference('/' + ApexPages.currentPage().getParameters().get('Id')); } return pf; }
- newbiewithapex
- February 20, 2019
- Like
- 0
how to write test class for method that fetches recommendations?
Below method fetch recommendations and I am not sure how to write test class for this method. Can someone please help me with this?
@AuraEnabled public static string getRecommendations(string recId) { string errorMessage; Recommendation__c rec = new Recommendation__c(); rec = [select Id, Name, Account__c, Account__r.Name, Account__r.RecordTypeId, Sub_Type__c, Opportunity__c, Description__c, Record_Type_Name__c from Recommendation__c where Id = :recId limit 1]; if (String.IsNOTBlank(rec.Opportunity__c)) { AuraHandledException e = new AuraHandledException(CS_UtilConstants__c.getValues('OPPTY_EXISTS_RECOMMENDATIONS_INFO').Value__c); e.setMessage(CS_UtilConstants__c.getValues('OPPTY_EXISTS_RECOMMENDATIONS_INFO').Value__c); throw e; } else if (rec.Record_Type_Name__c == CS_UtilConstants__c.getInstance('CONVERSION').Value__c && (rec.Description__c == Null || rec.Description__c == '') && (rec.Sub_Type__c == Null || rec.Sub_Type__c == '')) { AuraHandledException e = new AuraHandledException(CS_UtilConstants__c.getValues('CONVERSION ERROR MESSAGE').Value__c); e.setMessage(CS_UtilConstants__c.getValues('CONVERSION ERROR MESSAGE').Value__c); throw e; } return null; }
- newbiewithapex
- February 20, 2019
- Like
- 0
How to write test class for Webservice Callout?
I have this main class which uses webservice callout that I am not familiar with and I need to write test class for that. Can someone please help me figure out this one?
public BectranWebService.bectranServiceResult createCustomer(BectranWebService.bectranServiceRequest arg0) { BectranWebService.createCustomer request_x = new BectranWebService.createCustomer(); request_x.arg0 = arg0; BectranWebService.createCustomerResponse response_x = new BectranWebService.createCustomerResponse(); Map<String, BectranWebService.createCustomerResponse> response_map_x = new Map<String, BectranWebService.createCustomerResponse>(); response_map_x.put('response_x', response_x); WebServiceCallout.invoke( this, request_x, response_map_x, new String[]{endpoint_x, '', 'http://ws.services.bectran.com/', 'createCustomer', 'http://ws.services.bectran.com/', 'createCustomerResponse', 'BectranWebService.createCustomerResponse'} ); response_x = response_map_x.get('response_x'); return response_x.return_x; } public BectranWebService.additionalInfoBean getAdditionalAttributesForCreditApp(BectranWebService.loginInfoBean arg0,String arg1,String arg2) { BectranWebService.getAdditionalAttributesForCreditApp request_x = new BectranWebService.getAdditionalAttributesForCreditApp(); request_x.arg0 = arg0; request_x.arg1 = arg1; request_x.arg2 = arg2; BectranWebService.getAdditionalAttributesForCreditAppResponse response_x = new BectranWebService.getAdditionalAttributesForCreditAppResponse(); Map<String, BectranWebService.getAdditionalAttributesForCreditAppResponse> response_map_x = new Map<String, BectranWebService.getAdditionalAttributesForCreditAppResponse>(); response_map_x.put('response_x', response_x); WebServiceCallout.invoke(this, request_x, response_map_x, new String[]{endpoint_x, '', 'http://ws.services.bectran.com/', 'getAdditionalAttributesForCreditApp', 'http://ws.services.bectran.com/', 'getAdditionalAttributesForCreditAppResponse', 'BectranWebService.getAdditionalAttributesForCreditAppResponse' }); response_x = response_map_x.get('response_x'); return response_x.return_x; }
- newbiewithapex
- February 20, 2019
- Like
- 0
How do I write test class for a method that get events?
I have a method to get events and I am trying to figure out how to write test class for that method. Please check out the method below and let me know. Thanks!
@AuraEnabled /* Method to get events */ public static Event mGetEvent(string recordId) { Event evt = [SELECT Type, Subject, IsAllDayEvent, RecurrenceActivityId, Frequency_Details__c, Location, OwnerId, ActivityDate, Description, DurationInMinutes, RecordTypeId, RecordType.Name, EndDateTime, EventSubtype, WhoId, isRecurrence, IsPrivate, WhatId, ShowAs, StartDateTime, SC_Responsible__c, ROC_Primary_Deployment__c, RecurrenceType ,RecurrenceInterval ,Automatically_Extend_Recurring_Event__c,RecurrenceMonthOfYear,RecurrenceInstance,RecurrenceDayOfWeekMask ,RecurrenceDayOfMonth, FFC_Deployment_Type__c,Inside_Support__c, ROC_Comments_for_Other_Deployment__c, Reminder_Duration_LEX__c, Additional_Attendee_Type__c, Follow_Up_Required__c, FFC_Comments_for_Other__c FROM Event where id=: recordId LIMIT 1]; if(evt.IsAllDayEvent) { evt.StartDateTime = DateTime.newInstance(evt.StartDateTime.yearGMT(), evt.StartDateTime.monthGMT(), evt.StartDateTime.dayGMT(), 12, 0, 0); evt.EndDateTime = DateTime.newInstance(evt.EndDateTime.yearGMT(), evt.EndDateTime.monthGmt(), evt.EndDateTime.dayGMT(), 13, 0, 0); } return evt; }
- newbiewithapex
- February 19, 2019
- Like
- 0
how to write test class to cover getProfileName() method?
Here is my method and I need someone to helo me figure out how to write test class for this method.
@AuraEnabled
public static string getProfileName(){
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
return profileName;
}
@AuraEnabled
public static string getProfileName(){
Id profileId=userinfo.getProfileId();
String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
return profileName;
}
- newbiewithapex
- February 19, 2019
- Like
- 0
Code coverage dropped
public without sharing class EventInviteesCntrl { @AuraEnabled public List<EventRelation> invitees = new List<EventRelation>(); @AuraEnabled public List<String> accountCompanyDtls = new List<String>(); @AuraEnabled public List<boolean> redLeadsWithoutEmail = new List<boolean>(); @AuraEnabled public static List<EventRelation> getEventInvitees(String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Id recordId = (Id)eventId; String sObjectUsed = recordId.getSObjectType().getDescribe().getName(); if(sObjectUsed.equalsIgnoreCase('Event')){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId ORDER BY Relation.Name ASC LIMIT 5]; } else{ Event cbrEvent = [SELECT Id, CBR__c FROM Event WHERE CBR__c = :eventId LIMIT 1]; if(cbrEvent!=null){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :cbrEvent.Id ORDER BY Relation.Name ASC LIMIT 5]; } } return inviteesList; } @AuraEnabled public static List<EventRelation> getAllEventInvitees(String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Id recordId = (Id)eventId; String sObjectUsed = recordId.getSObjectType().getDescribe().getName(); if(sObjectUsed.equalsIgnoreCase('Event')){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId ORDER BY Relation.Name ASC]; } else { Event cbrEvent = [SELECT Id, CBR__c FROM Event WHERE CBR__c = :eventId LIMIT 1]; if(cbrEvent!=null){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :cbrEvent.Id ORDER BY Relation.Name ASC]; } } return inviteesList; } @AuraEnabled public static Integer getTotalEventInvitees (String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); inviteesList = getAllEventInvitees(eventId); return inviteesList.size(); } @AuraEnabled public static String getApproxEventInvitees (String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Integer size = getTotalEventInvitees(eventId); if(size > 3){ return ('3+'); } else{ return(String.valueOf(size)); } } @AuraEnabled public static EventInviteesCntrl getInviteesDtls (String eventId) { System.debug('get invitees dtls -->'+eventId); EventInviteesCntrl obj = new EventInviteesCntrl(); obj.invitees = getAllEventInvitees(eventId); obj.redLeadsWithoutEmail = initListBool(obj.invitees.size()); Integer counter = 0; for(EventRelation eveRel : obj.invitees){ if(eveRel.Relation.Type == 'Contact'){ Contact con = [select id, Account.Name, email from Contact where id = :eveRel.RelationId]; if(con.email == null || con.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } obj.accountCompanyDtls.add(con.Account.Name); } else if(eveRel.Relation.Type == 'Lead'){ Lead lead = [select id, email, Company from Lead where id = :eveRel.RelationId]; if(lead.email == null || lead.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } obj.accountCompanyDtls.add(lead.Company); } else if(eveRel.Relation.Type == 'User'){ User user = [select id, CompanyName, email from User where id = :eveRel.RelationId]; if(user.email == null || user.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } if(user.CompanyName!=null && user.CompanyName!=''){ obj.accountCompanyDtls.add(user.CompanyName); } else{ obj.accountCompanyDtls.add('US Foods'); } } counter++; } return obj; } @AuraEnabled public static void mRemoveInvitee(String removedEveRelID) { EventRelation deletingEveRel = [Select id, RelationId from EventRelation where id= :removedEveRelID]; Database.delete(deletingEveRel); } @AuraEnabled public static UnsavedSelectedInvitee[] mPostAdditionOfInvitees(List<String> selectedInviteesIDs) { List<UnsavedSelectedInvitee> unsavedSelectedInvitees = new List<UnsavedSelectedInvitee>(); for(String sObjID : selectedInviteesIDs){ String sObjAPIName = (Id.valueOf(sObjID)).getSObjectType().getDescribe().getName(); if(sObjAPIName.equalsIgnoreCase('Contact')){ Contact con = [SELECT id,name,Account.Name, email from Contact where id= :sObjID]; if(con.email == null || con.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), con.Name, con.Account.Name, 'Contact',true)); } else { unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), con.Name, con.Account.Name, 'Contact')); } } else if(sObjAPIName.equalsIgnoreCase('User')){ User user = [SELECT id,Name,CompanyName, email from User where id= :sObjID]; if(user.CompanyName!=null && user.CompanyName!=''){ if(user.email == null || user.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, user.CompanyName, 'User', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, user.CompanyName, 'User')); } } else{ if(user.email == null || user.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, 'US Foods', 'User', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, 'US Foods', 'User')); } } } else if(sObjAPIName.equalsIgnoreCase('Lead')){ Lead lead = [SELECT id,name,Company,email from Lead where id= :sObjID]; if(lead.email == null || lead.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), lead.Name, lead.Company, 'Lead', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), lead.Name, lead.Company, 'Lead')); } } } return unsavedSelectedInvitees; } @AuraEnabled public static List<EventTracker> checkUserAvailability (DateTime currEventStart, List<String> inviteeIDs) { System.debug('Event start -->'+currEventStart); List<EventTracker> eventsTrack = new List<EventTracker>(); List<boolean> slotsBooked; if(currEventStart == null){ currEventStart = System.now(); } DateTime conditional_start = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(06,00,00,000)); DateTime conditional_end = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(23,00,00,000)); DateTime conditional_starts = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(00,00,00,000)); DateTime conditional_ends = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(23,00,00,000)); for(String invitee : inviteeIDs){ System.debug('Invitees -->'+invitee); slotsBooked = initListBool(72); List<Id> todayEvents = new List<Id>(); for (Event tdEvt : [Select Id FROM Event Where StartDateTime >= :conditional_start AND EndDateTime <= :conditional_end ORDER BY StartDateTime LIMIT 10000]) { todayEvents.add(tdEvt.Id); } System.debug('todayEvents'+todayEvents); List<Id> userInvites = new List<Id>(); for (EventRelation evtInv : [SELECT EventId FROM EventRelation WHERE RelationId = :invitee AND EventId IN :todayEvents]){ userInvites.add(evtInv.EventId); } system.debug('todays events where they are an invitee-->' + userInvites); System.debug('Event '); List<Event> userEvents = [SELECT Id, OwnerID, Owner.Name, Subject, ActivityDateTime, ActivityDate, DurationInMinutes, StartDateTime, EndDateTime, Description, WhatID, What.Name, WhoID, Who.Name, isAllDayEvent FROM Event where (CreatedById = :invitee and StartDateTime >= :conditional_start and EndDateTime <= :conditional_end) OR ID IN :userInvites OR (CreatedById = :invitee and StartDateTime >= :conditional_starts and EndDateTime <= :conditional_ends)]; System.debug('User Events-->'+userEvents); for(Event usrEve : userEvents){ Integer index = (usrEve.StartDateTime.hour() - 6) *4; DateTime counterDt = usrEve.StartDateTime; boolean isLastQuarter = false; if(usrEve.DurationInMinutes >= 1440) { for(Integer i=0; i<slotsBooked.size();i++){ slotsBooked.set(i,true); } } else { for(Integer i=0; i<usrEve.DurationInMinutes; ){ if(index >= 0){ if(counterDt.minute()>=0 && counterDt.minute()<15){ if(!isLastQuarter){ slotsBooked.set(index+0, true); } else if(isLastQuarter && index > 0){ slotsBooked.set(index-1, true); } } if(counterDt.minute()>= 15 && counterDt.minute()<30){ slotsBooked.set(index+1, true); if(isLastQuarter){ slotsBooked.set(index, true); } } if(counterDt.minute()>= 30 && counterDt.minute()<45){ slotsBooked.set(index+2, true); } if(counterDt.minute()>= 45){ slotsBooked.set(index+3, true); } } System.debug('Counter Date : '+counterDt+' ,Index Position : '+index+' ,i : '+i); counterDt = counterDt.addMinutes(15); if(counterDt.minute()==0){ isLastQuarter = true; } index = (counterDt.hour() - 6) *4; i+=15; } } } eventsTrack.add(new EventTracker(Id.valueOf(invitee), slotsBooked)); System.debug('SlotsBooked-->'+slotsBooked); } return eventsTrack; } @AuraEnabled public static void saveInvitees (boolean saveAllEvents, String eventId, String inviteesJson) { String eventIdToMap = eventId;//added by Nimitha for defect 583. List<Id> userInvitees = new List<Id>(); if(eventId!=null && inviteesJson!=null && eventId!='' && inviteesJson!=''){ Event eve = [SELECT id, subject, isRecurrence, StartDateTime, EndDateTime, location, RecurrenceActivityId, isAllDayEvent, Frequency_Details__c FROM Event WHERE id= :eventId LIMIT 1]; List<UnsavedSelectedInvitee> inviteesList = (List<UnsavedSelectedInvitee>)JSON.deserialize(inviteesJson, List<UnsavedSelectedInvitee>.class); List<EventRelation> eventRelations = new List<EventRelation>(); if(saveAllEvents!=null && saveAllEvents==true){ eventId = eve.RecurrenceActivityId; } for(UnsavedSelectedInvitee invitee : inviteesList){ EventRelation eveRel = new EventRelation(); eveRel.RelationId = invitee.sObjID; if(String.isBlank(eventId)){ eveRel.eventId = eventIdToMap; }else{ eveRel.eventId = eventId; } eventRelations.add(eveRel); if(invitee.sObjID.getSObjectType().getDescribe().getName() == 'User'){ userInvitees.add(invitee.sObjID); } } if(!eventRelations.isEmpty()){ Database.DMLOptions dlo = new Database.DMLOptions(); dlo.EmailHeader.triggerUserEmail = false; dlo.EmailHeader.triggerOtherEmail = true; Database.insert(eventRelations, dlo); System.debug('Sending email...'); sendEmail(userInvitees, eve); } } else{ throw new AuraHandledException('Looks like some Exception has occured, kindly try again'); } } @AuraEnabled public static void saveInviteesDirectly (string eventId, List<String> addedInviteesId) { addedInviteesId.remove(0); List<Id> userInvitees = new List<Id>(); if(eventId!=null && eventId!='' && !addedInviteesId.isEmpty()){ Event eve = [SELECT id, subject, StartDateTime, EndDateTime, location, isAllDayEvent, IsRecurrence, Frequency_Details__c FROM Event WHERE id= :eventId LIMIT 1]; List<EventRelation> eventRelations = new List<EventRelation>(); for(String invitee : addedInviteesId){ if(invitee != null && invitee!=''){ EventRelation eveRel = new EventRelation(); eveRel.RelationId = invitee; eveRel.eventId = eventId; eventRelations.add(eveRel); if((Id.valueOf(invitee)).getSObjectType().getDescribe().getName() == 'User'){ userInvitees.add(Id.valueOf(invitee)); } } } if(!eventRelations.isEmpty()){ Database.DMLOptions dlo = new Database.DMLOptions(); dlo.EmailHeader.triggerUserEmail = false;dlo.EmailHeader.triggerOtherEmail = true; Database.insert(eventRelations, dlo); sendEmail(userInvitees, eve); } } else{ throw new AuraHandledException('Looks like some Exception has occured, kindly try again'); } } @AuraEnabled public static List<String> getTimes (DateTime startDateTime, DateTime endDateTime) { List<String> times = new List<String>(); String str0; String str1; String str2; if(startDateTime==null||endDateTime==null){ startDateTime = System.now(); endDateTime = System.now(); } String startDt = startDateTime.format('yyyy-MM-dd hh:mm a'); String endDt = endDateTime.format('yyyy-MM-dd hh:mm a'); str0 = String.valueOf(startDateTime.format('MMM dd, yyyy')); if(startDt.contains('AM')){ str1 = (startDateTime.hour()==0 ? 12 : startDateTime.hour()) + ':'+startDateTime.minute() + ' AM'; if(startDateTime.minute() < 10){ str1 = (startDateTime.hour()==0 ? 12 : startDateTime.hour()) + ':'+startDateTime.minute() + '0 AM'; } } else if(startDt.contains('PM')){ str1 = (startDateTime.hour()==12 ? startDateTime.hour() : (startDateTime.hour()-12)) + ':'+startDateTime.minute() + ' PM'; if(startDateTime.minute() < 10){ str1 = (startDateTime.hour()==12 ? startDateTime.hour() : (startDateTime.hour()-12)) + ':'+startDateTime.minute() + '0 PM'; } } if(startDateTime.day() == endDateTime.day()){ if(endDt.contains('AM')){ str2 = (endDateTime.hour()==0 ? 12 : endDateTime.hour()) + ':'+endDateTime.minute() + ' AM'; if(endDateTime.minute() < 10){ str2 = (endDateTime.hour()==0 ? 12 : endDateTime.hour()) + ':'+endDateTime.minute() + '0 AM'; } } else if(endDt.contains('PM')){ str2 = (endDateTime.hour()==12 ? endDateTime.hour() : (endDateTime.hour()-12)) + ':'+endDateTime.minute() + ' PM'; if(endDateTime.minute() < 10){ str2 = (endDateTime.hour()==12 ? endDateTime.hour() : (endDateTime.hour()-12)) + ':'+endDateTime.minute() + '0 PM'; } } } else{ str2 = '11:59 PM';} times.add(str0); times.add(str1); times.add(str2); return times; } @AuraEnabled public static boolean validateInternalUserIfInvited(String eventId) { List<EventRelation> eveRelList = getAllEventInvitees(eventId); for(EventRelation eveRel : eveRelList){ if(eveRel.RelationId == UserInfo.getUserId()){//checking if LoggedIn User is invited return true; } } return false; } @AuraEnabled public static void processUserInviteeResponse(String eventId, boolean isAccepted){ EventRelation eveRel = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId AND RelationId = :UserInfo.getUserId() limit 1]; if(isAccepted){ eveRel.Status = 'Accepted'; eveRel.RespondedDate = System.now(); } else if(!isAccepted){ eveRel.Status = 'Declined'; eveRel.RespondedDate = System.now(); } Database.update(eveRel); } public static void sendEmail(List<Id> userInvitees, Event currEvent) { List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>(); String eventRedirectURL = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + currEvent.Id; for(Id inviteeId : userInvitees){ Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); User user = [SELECT Id, TimeZoneSidKey FROM User WHERE Id=:inviteeId]; String eventRedirectURL_accept = System.URL.getSalesforceBaseUrl().toExternalForm() + '/c/ResponseMgmt.app?eventId='+currEvent.Id+'&userId='+inviteeId+'&response=Accepted'; String eventRedirectURL_decline = System.URL.getSalesforceBaseUrl().toExternalForm() + '/c/ResponseMgmt.app?eventId='+currEvent.Id+'&userId='+inviteeId+'&response=Declined'; List<String> displayUserTime = getTimes(currEvent.StartDateTime, currEvent.EndDateTime, user.TimeZoneSidKey, currEvent.IsAllDayEvent); email.setTargetObjectId(inviteeId); if(currEvent.isRecurrence){ email.setSubject('Recurring Event Invitation : '+currEvent.Subject); } else{ email.setSubject('Meeting Request : '+currEvent.Subject); } if(currEvent.IsAllDayEvent){ if(currEvent.isRecurrence){ email.setHTMLBody(' <b>Recurring Event Invitation</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+currEvent.Frequency_Details__c+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } else{ email.setHTMLBody(' <b>Meeting Request</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+displayUserTime.get(0)+' '+displayUserTime.get(1)+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } } else{ if(currEvent.IsRecurrence){ email.setHTMLBody(' <b>Recurring Event Invitation</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+currEvent.Frequency_Details__c+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } else{ email.setHTMLBody(' <b>Meeting Request</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+displayUserTime.get(0)+' '+displayUserTime.get(1)+' - '+displayUserTime.get(2)+' '+getTimeZoneValue(user.TimeZoneSidKey)+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } } email.setSaveAsActivity(false); emailList.add(email); } Messaging.sendEmail(emailList,false); } public static List<String> getTimes (DateTime startDateTime, DateTime endDateTime, String timeZone, boolean isAllDayEvent) { System.debug('####StartDate before Formatting - '+startDateTime); List<String> times = new List<String>(); String str0; String str1; String str2; if(startDateTime==null||endDateTime==null){ startDateTime = System.now(); endDateTime = System.now(); } if(timeZone==null||timeZone==''){ timeZone = 'GMT'; } if(!isAllDayEvent){ String startDt = startDateTime.format('MM/dd/yyyy hh:mm a', timeZone); String endDt = endDateTime.format('MM/dd/yyyy hh:mm a', timeZone); List<String> startDtItems = startDt.split(' '); List<String> endDtItems = endDt.split(' '); str0 = startDtItems.get(0); System.debug('####StartDate after Formatting - '+str0); str1 = startDtItems.get(1) + ' ' + startDtItems.get(2); str2 = endDtItems.get(1) + ' ' + endDtItems.get(2); } else if(isAllDayEvent){ DateTime startDt_mod = startDateTime.addHours(12); str0 = startDt_mod.format('MM/dd/yyyy', timeZone); str1 = 'All-Day Event'; } times.add(str0); times.add(str1); times.add(str2); return times; } public static String getTimeZoneValue(String timeZone) { List<String> tzLabel; String returnStr=''; Schema.DescribeFieldResult fieldResult = User.TimeZoneSidKey.getdescribe(); List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); for(Schema.PicklistEntry p : ple) { if(p.getValue().equals(timeZone)){ tzLabel = p.getlabel().split(' '); for(Integer i=0; i<tzLabel.size(); i++) { if(i==0 || i==tzLabel.size()-1){ continue; } else{ returnStr += tzLabel.get(i)+' '; } } return returnStr; } } return 'GMT'; } public static List<boolean> initListBool(Integer size){ List<boolean> boolList = new List<boolean>(); for(Integer i=0; i<size; i++){ boolList.add(false); } System.debug('SlotsInit-->'+boolList); return boolList; } public class UnsavedSelectedInvitee{ @AuraEnabled public Id sObjID {get; set;} @AuraEnabled public String inviteeName {get; set;} @AuraEnabled public String accountCompany {get; set;} @AuraEnabled public String inviteeType {get; set;} @AuraEnabled public boolean isLeadWithoutEmail {get; set;} public UnsavedSelectedInvitee(Id sObjID, String inviteeName, String accountCompany, String inviteeType){ this.sObjID = sObjID; this.inviteeName = inviteeName; this.accountCompany = accountCompany; this.inviteeType = inviteeType; this.isLeadWithoutEmail = false; } public UnsavedSelectedInvitee(Id sObjID, String inviteeName, String accountCompany, String inviteeType, boolean isLeadWithoutEmail){ this.sObjID = sObjID; this.inviteeName = inviteeName; this.accountCompany = accountCompany; this.inviteeType = inviteeType; this.isLeadWithoutEmail = isLeadWithoutEmail; } } class EventTracker{ @AuraEnabled public Id inviteeID {get; set;} @AuraEnabled public List<boolean> isCurrentSlotBooked {get; set;} public EventTracker(Id inviteeID, List<boolean> isCurrentSlotBooked){ this.inviteeID = inviteeID; this.isCurrentSlotBooked = isCurrentSlotBooked; } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class method to cover If loop?
I am trying cover if loop from EventHandler class but I can't figurer out why this part of the code is not covered. Test class is way too long to post it here so can someone please help me with this?
if(eveRels !=null && eveRels.size()>0){ for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I cover if and for loop from EventHandler class from test class?
I have this EventHandler class that I am trying to increse code coverage. I need help figuring out how to handle this if loop.
if(eveRels !=null && eveRels.size()>0){ for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class method to cover If loop from EventHandler class?
I have the test class that is covering most of the EventHandler class but just missing this if loop coverage. Unfortunatly both classes are too big to post here. Can someone help me with this please?
if (Limits.getQueries() < Limits.getLimitQueries() && !eventOwnerIdSet.isEmpty()) { if (userMap == null) { userMap = new Map<Id, User> ([select Id, Sales_Coordinator__c, ProfileId from User]); } for (Event e: scEventList) { if (string.isNOTblank(userMap.get(e.ownerId).Sales_Coordinator__c)) { // current event owner must have an SC if (e.IsRecurrence ) { // if recurring event series e.ownerId = userMap.get(e.ownerId).Sales_Coordinator__c; System.debug('EventId1' +e.Id); processedRecEventIds.add(e.Id); // add series parent id to avoid processing the child records } else if (e.RecurrenceActivityId != null && !e.IsRecurrence) { // if recurring event child System.debug('EventId' +e.Id); Event parentEvt = [Select id, ownerId, whoId, isRecurrence from Event where id= :e.RecurrenceActivityId and isRecurrence=true]; //parentEvt.ownerId = userMap.get(parentEvt.ownerId).Sales_Coordinator__c; //update parentEvt; system.debug('####New Owner - '+parentEvt.ownerId); processedRecEventIds.add(parentEvt.id); } } else if ((e.IsRecurrence || !processedRecEventIds.contains(e.RecurrenceActivityId) || String.isBlank(e.RecurrenceActivityId)) && userMap.get(memberIdSCIdMap.get(e.Bulk_Item_Indicator__c)).ProfileId != SalesforceIds__c.getOrgDefaults().Profile_USF_SalesCoordinator__c){ } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class for this class?
I need to write test class for the below class. How do I do that?
public class DataUtil{ private static final String am_time = 'AM'; private static final String empty_Space = ' '; private static final String split_Time = '\\:'; private static final string number_Twelve = '12'; public static Map<Id, Account> populateAccountData(Set<Id> idsSet) { Map<Id,Account> accountDataMap = new Map<Id,Account>(); Map<String, String> sObjAndAccFld = new Map<String, String>(); Map<String, Set<Id>> sObjAndIdsMap = new Map<String, Set<Id>>(); Map<id,Set<id>> ridAndAccIDMap = new Map<id,Set<id>>(); Set<Id> accountIdsSet = new Set<Id>(); for(Id recId: idsSet) {//Iteraing the all Related Ids system.debug('SSSSSSS : '+String.valueOf(recId.getSobjectType())); String sObjName = String.valueOf(recId.getSobjectType()); if(sObjAndIdsMap.containsKey(sObjName)) { // checking and adding the related id to the appropriate sObject sObjAndIdsMap.get(sObjName).add(recId); } else { Set<Id> idst = new Set<Id> {recId}; sObjAndIdsMap.put(sObjName,idst); } if(sObjName == 'Account') { //If related Id is ACCOUNT Id then add it to the accountIdsSet accountIdsSet.add(recId); Set<Id> ridSet = new Set<Id> {recId}; ridAndAccIDMap.put(recId,ridSet); } else {//If related Id is NOT ACCOUNT Id then finding the Id related to which object List<Schema.DescribeSObjectResult> describeObj = Schema.describeSObjects(new String[]{sObjName}); Map<String, Schema.SObjectField> FsMap = describeObj[0].fields.getMap(); for (Schema.SObjectField objField: FsMap.values()) { Schema.DescribeFieldResult fieldDesc = objField.getDescribe(); List<Schema.sObjectType> referenceObj = fieldDesc.getReferenceTo(); if(!referenceObj.isEmpty()){ // determine if field is a lookup field if(referenceObj[0].getDescribe() == Schema.SObjectType.Account){ // determine if field is a lookup to Account object String acctFieldName = fieldDesc.getName(); // get field API name of the account lookup field sObjAndAccFld.put(sObjName, acctFieldName); break; } } } } } for(String objName : sObjAndAccFld.keySet()) {// Building Dynamic quesy and Ferching the Account Id based on the relaed object Set<Id> recIds = sObjAndIdsMap.get(objName); String fieldAPIName = sObjAndAccFld.get(objName); string soql = 'select id, '+fieldAPIName+' from '+objName+' where id IN: recIds'; system.debug('QQQQQuery : '+soql); for(sObject sObj: database.query(soql)) { //added new condition on 5/3 to check if account is null refer D 1159 if(sObj.get(fieldAPIName) != null){ accountIdsSet.add((id)sObj.get(fieldAPIName));// to query the account data adding the account id to accountIdsSet } if(ridAndAccIDMap.containsKey((Id)sObj.get(fieldAPIName))) {//to map related Id and account Id (One account may have multiple related Ids) ridAndAccIDMap.get((Id)sObj.get(fieldAPIName)).add((Id)sObj.get('id')); } else { Set<Id> ridSet = new Set<Id> {(Id)sObj.get('id')}; ridAndAccIDMap.put((Id)sObj.get(fieldAPIName),ridSet); } } } if(!accountIdsSet.isEmpty()) { Map<Id,Account> accountsMap = new Map<Id,Account>([select id, name, Service_Model_Indicator__c, Account_Status__c from Account where Id IN: accountIdsSet]); for(Id aid: ridAndAccIDMap.keySet()) { // to get account data in task or event handler based on the related Id we are adding them to map, for(Id rid : ridAndAccIDMap.get(aid)) { accountDataMap.put(rid, accountsMap.get(aid)); } } } return accountDataMap; } /* Method Name: FindAreaRole * Return Type: String * Parameters : String divisionNumber * Description: This method is used retur */ public static String findArea(String divisonNumber){ String areaRoleId = ''; UserRole userRole=[Select Id,ParentRoleId,Name from UserRole where Name = : divisonNumber]; areaRoleId = String.valueOf(userRole.ParentRoleId); return areaRoleId; } /* Method Name: getChildRoles * Return Type: Set<Id> * Parameters : String parentRoleId * Description: getChildRoles takes in the parentRoleId and returns set of childRoleIds. parentRoleId is not included in the set. */ public static Set<Id> getChildRoles (string parentRoleId) { Map <String,Set<Id>> roleMap = new Map <string,Set<Id>>(); // Build Map of Parent Role Id as the key with a set of it's immidiate child records as the value of the map for (UserRole roles : [Select ParentRoleId, Id From UserRole where ParentRoleId != null]) { if(roleMap.containsKey(roles.ParentRoleId) ) { roleMap.get(roles.ParentRoleId).add(roles.Id); } else { roleMap.put(roles.ParentRoleId, new Set<ID>{roles.Id}); } //system.debug('Parent: ' + roles.ParentRoleId); //system.debug('Set of child: ' + roleMap.get(roles.ParentRoleId)); } Set<Id> childRoles = getRoleSubordinateSet (roleMap,parentRoleId); //system.debug('Set of all childRoles: '+ childRoles); return childRoles; } /* Method Name: getRoleSubordinateSet * Return Type: Set<Id> * Parameters : Map of <ParentRoleId, Set of immidiate child records>, string of roleId * Description: Internal recursive method that will return a set of subordinate childRoleIds */ private static Set<Id> getRoleSubordinateSet (Map <String,Set<Id>> mapRoles, string roleId) { Set<Id> childRoles = new Set<id>(); //RK : the below line of code RoleId is added to check if the assigned to role and logged in user role division number childRoles.add(roleId); if(mapRoles.containsKey(roleId)) { for(Id id : mapRoles.get(roleId)) { childRoles.add(id); //recursive call childRoles.addAll(getRoleSubordinateSet(mapRoles,id)); } } return childRoles; } /* Method Name: getUserRoleNames * Return Type: Map<Id, String> * Parameters : Set<Id> UserId * Description: getUserRoleNames takes in a set of user Ids and returns a Map with <Id:User Id, String:User Role Name> */ public static Map<Id, String> getUserRoleNames(Set<Id> UserIds) { try{ Map<Id, String> UserRoleNames = new Map<Id, String>(); for(User usr: [SELECT UserRole.Name FROM User WHERE Id = :UserIds]){ UserRoleNames.put(usr.id, usr.UserRole.Name); } return UserRoleNames; } catch(Exception e) { return null; } } /** * Method Name : buildTime * arguments : String * returnType : Datetime */ public static Datetime buildTime(String rawTime){ Integer hrs; Integer mns; if(rawTime.endsWith(am_time)){ String tme = rawTime.split(empty_Space)[0]; List<String> tmestring = tme.split(split_Time); if(tmestring[0] == number_Twelve){ hrs = 0; mns = Integer.valueOf(tmestring[1]); } else { hrs = Integer.valueOf(tmestring[0]); mns = Integer.valueOf(tmestring[1]); } } else { String tme = rawTime.split(empty_Space)[0]; List<String> tmestring = tme.split(split_Time); if(tmestring[0] == number_Twelve){ hrs = Integer.valueOf(tmestring[0]); mns = Integer.valueOf(tmestring[1]); } else { hrs = Integer.valueOf(tmestring[0])+12; mns = Integer.valueOf(tmestring[1]); } } date dt = date.today(); Datetime finalDT = Datetime.newInstance(dt.year(), dt.month(), dt.day(), hrs, mns, 0); // system.debug('FFInal time'+finalDT); return finalDT; } /* Method Name: getRoleSubordinateUsers * Return Type: Map<Id, String> * Parameters : Set<Id> UserId * Description: getUserRoleNames takes in a Role Ids and returns a set of user Ids */ public static Set<ID> getRoleSubordinateUsers(Id roleId) { // get all of the roles underneath the user Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId}); // get all of the ids for the users in those roles Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where UserRoleId IN :allSubRoleIds]); // return the ids as a set so you can do what you want with them return users.keySet(); } /* Method Name: getAllSubRoleIds * Return Type: Set<Id> currentRoleIds * Parameters : Set<Id> currentRoleIds * Description: getAllSubRoleIds takes in a set of role Ids and returns set of all Subordinate Role Ids */ private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) { Set<ID> currentRoleIds = new Set<ID>(); // get all of the roles underneath the passed roles for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null]) currentRoleIds.add(userRole.Id); // go fetch some more rolls! if(currentRoleIds.size() > 0) currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds)); return currentRoleIds; } }
- newbiewithapex
- February 18, 2019
- Like
- 0
How do I create test class for Task assignment method?
I have here the helper class to create task based on custom setting. How do I write test class for this methods in main class. Here is my main
public class PMO_Task_Assignment { public static void PMO_Task_Assignment(List<IDC_Task__c> lstTask){ // Map to get task order vs. custom setting value Map<String, PMO_TaskAssignment__c> alltasks = PMO_TaskAssignment__c.getAll(); // Map to get values to create defect Map<String, PMO_CreateDefect__c> alldefects = PMO_CreateDefect__c.getAll(); // Map to get task type vs completed IDC Task Map<String, IDC_Task__c> tasks = new Map<String, IDC_Task__c>(); // List of new Task Types List<string> lstnewtasktype = new List<string>(); // List of completed IDC Tasks List<IDC_Task__c> lstexistingTask = new List<IDC_Task__c>(); // List of new IDC Tasks List<IDC_Task__c> lstnewTask = new List<IDC_Task__c>(); // Creating a Map of Task type and completed IDC Task for(IDC_Task__c t: lstTask) { if(alltasks.containskey(t.Task_Type__c)){ tasks.put(PMO_TaskAssignment__c.getInstance(t.task_type__c).Task__c,t); } } // Looping through all values in custom setting and creating list of new task types as well as completed tasks in same order for(PMO_TaskAssignment__c task : alltasks.values()) { if(tasks.containskey(PMO_TaskAssignment__c.getInstance(task.name).Preceding_Task__c)){ lstnewtasktype.add(PMO_TaskAssignment__c.getInstance(task.name).Task__c); lstexistingTask.add(tasks.get(PMO_TaskAssignment__c.getInstance(task.name).Preceding_Task__c)); } } List<Defect__c> lstdefect = new List<Defect__c>(); // Creating new tasks and adding them in the list for(integer counter=0;counter<lstnewtasktype.size();counter++){ if(lstnewtasktype[counter] != system.label.PMO_Task_CodeReview || (lstnewtasktype[counter] == system.label.PMO_Task_CodeReview && lstexistingTask[counter].Build_Task_Type__c == system.label.PMO_TaskType_Customization)){ IDC_Task__c IDCTask = new IDC_Task__c(); //if(!TL.isEmpty()) if(PMO_TaskAssignment__c.getInstance(lstnewtasktype[counter]).Owner_Queue__c != null){ IDCTask.OwnerId = PMO_TaskAssignment__c.getInstance(lstnewtasktype[counter]).Owner_Queue__c; } IDCTask.Assigned_Date__c = system.today(); IDCTask.Task_Type__c = lstnewtasktype[counter]; IDCTask.IDC_Task__c = lstexistingTask[counter].id; IDCTask.Track__c = lstexistingTask[counter].Track__c; IDCTask.Request__c = lstexistingTask[counter].Request__c; if((lstexistingTask[counter].Defect_Found__c == true && (lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Review) || lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Execution))) || (!lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Review) && !lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Execution))) lstnewtask.add(IDCTask); } try{ if( lstexistingTask[counter].Defect_Found__c == true && lstexistingTask[counter].Defect_Description__c != null && PMO_CreateDefect__c.getInstance(lstexistingTask[counter].Task_Type__c).Create_Defect__c == true){ Defect__c dfct = new Defect__c(); Dfct.subject__c = system.label.PMO_Defect_Subject + lstexistingTask[counter].Request_Name__c; Dfct.status__c = system.label.PMO_Defect_Open; Dfct.Defect_Detected__c = lstexistingTask[counter].Task_Type__c; Dfct.Detailed_Description__c = lstexistingTask[counter].Defect_Description__c; if(lstexistingTask[counter].Request__c != null) Dfct.Related_Request__c = lstexistingTask[counter].Request__c; lstdefect.add(Dfct); } } catch(exception ex){ ex.setMessage(system.label.PMO_Task_Error); } } // insert the list if(!lstnewtask.isEmpty()) { try { insert lstnewtask; insert lstdefect; } catch(DMLException ex){ ex.setMessage(system.label.PMO_Task_Error); } } } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How do I write test class for sort methods?
I have a class which has different sort methods and I need help writing test class for those methods. Here is my main class.
public class TrialCustomerPortalHomePageController { User loggedInUser = [Select id,contactId,Contact.AccountId from User where id = :UserInfo.getUserId()]; public List<Asset> MyRegisteredProducts {get; set;} public List<Case> MyRecentCases {get; set;} public List<Solution> TopSolutions {get; set;} public List<Idea> PopularIdeas {get; set;} public String sortField1 {get; set;} public String previousSortField1 {get; set;} public String sortField2 {get; set;} public String previousSortField2 {get; set;} public String sortField3 {get; set;} public String previousSortField3 {get; set;} public String sortField4 {get; set;} public String previousSortField4 {get; set;} public TrialCustomerPortalHomePageController() { MyRegisteredProducts = [select id,Name,SerialNumber,InstallDate,UsageEndDate,Status from Asset where ContactId = :loggedInUser.ContactId order by SerialNumber desc limit 3]; MyRecentCases = [select id,CaseNumber,Subject,Status,LastModifiedDate from Case where ContactId = :loggedInUser.ContactId order by LastModifiedDate desc limit 3]; TopSolutions = [select id,SolutionName,TimesUsed,LastModifiedDate from Solution order by TimesUsed desc limit 3]; PopularIdeas = [select id,Title,Categories,VoteTotal from Idea order by VoteTotal desc limit 3]; } public void SortProducts(){ String order = 'asc'; if(previousSortField1 == sortField1){ order = 'desc'; previousSortField1 = null; }else{ previousSortField1 = sortField1; } superSort.sortList(MyRegisteredProducts,sortField1,order); } public void SortCases(){ String order = 'asc'; if(previousSortField2 == sortField2){ order = 'desc'; previousSortField2 = null; }else{ previousSortField2 = sortField2; } superSort.sortList(MyRecentCases,sortField2,order); } public void SortSolutions(){ String order = 'asc'; if(previousSortField3 == sortField3){ order = 'desc'; previousSortField3 = null; }else{ previousSortField3 = sortField3; } superSort.sortList(TopSolutions,sortField3,order); } public void SortIdeas(){ String order = 'asc'; if(previousSortField4 == sortField4){ order = 'desc'; previousSortField4 = null; }else{ previousSortField4 = sortField4; } superSort.sortList(PopularIdeas,sortField4,order); } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How do I write test class for contact search method?
I have a main class that search contact records and I am looking for any help on how to write test class for this method. Here is my main class look like. I am not fimiliar with @RestResource and @HttpGet.
@RestResource(urlMapping='/contactsSearch/*') global without sharing class REST_GetContactsSearch { @HttpGet global static ContactList doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String term = RestContext.request.params.get('term'); String contactQueryStr = 'SELECT Name,Id,Title,Email,Phone,MobilePhone,Account.Name,PhotoUrl FROM Contact WHERE Email != null AND OwnerId = \'' + UserInfo.getUserId() + '\' AND IsDeleted = false'; if(!String.isEmpty(term) && term.length() >= 2){ term = '%' + term + '%'; contactQueryStr += ' AND Name LIKE \'' + term + '\''; } System.debug('@@@@ contactQueryStr: ' + contactQueryStr); List<Contact> contacts = Database.query(contactQueryStr); ContactList contactsList = new ContactList(); contactsList.contacts = contacts; return contactsList; } global class ContactList { public List<Contact> contacts; public ContactList () { contacts = null; } } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How to write test class to validate customer order?
I have this class as a controller for the customer order validate component . I need help writing test class for this one. Any kind of help would be much appreciate.
public class CustomerOrderValidateCntrl { @AuraEnabled public static UserNAccountDetails getParamDetails(String accId) { Account acc = getAccountDetails(accId); boolean profilecheckfailed = false; profilecheckfailed = isProfileNotToBeAllowed(); system.debug('Tandem: '+acc.Tandem_Account_Number__c); return new UserNAccountDetails(profilecheckfailed,acc.Tandem_Account_Number__c,acc.Division_Number__c,getUserDetails()); } public static Account getAccountDetails(String accId) { return [SELECT Id, Tandem_Account_Number__c, Division_Number__c FROM Account WHERE Id = :accId LIMIT 1]; } public static String getUserDetails() { User usr = [SELECT Id, Network_Id__c FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1]; return usr.Network_Id__c; } public static boolean isProfileNotToBeAllowed(){ SalesforceIds__c profileIds = SalesforceIds__c.getOrgDefaults(); return (UserInfo.getProfileId().contains(profileIds.Profile_USF_ChefStoreRep__c)); } public class UserNAccountDetails{ @AuraEnabled public Boolean profileCheckFailed {set;get;} @AuraEnabled public String tandemNumber {set;get;} @AuraEnabled public String divisionNumber {set;get;} @AuraEnabled public String networkId {set;get;} public UserNAccountDetails(Boolean profileCheckFailed, String tandemNumber, String divisionNumber, String networkId){ this.profileCheckFailed=profileCheckFailed; this.tandemNumber=tandemNumber; this.divisionNumber=divisionNumber; this.networkId=networkId; } } }
- newbiewithapex
- February 13, 2019
- Like
- 0
How do I cover part of the main class code in test class?
I have the Lead converter class and I am stuck on the part where the loop checks the LeadRecordType. Any help is much appreciated
This is the main class code
if (oppID != null) {
Opportunity opp = [select id, RecordTypeId, StageName from opportunity where id = :oppID];
system.debug('Initial StageName = ' + opp.StageName);
//get the oppty "Prospect - Locally Manager" Record type id from custom settings
if (recordTypeId != null) {
//Updated by ADUA to have different record types for Opportunity from Converted leads as per Lead Record Type
String oppRecordTypeId;
if (leadRecordType.Name == 'ChefStore') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Locally_Managed__c;
opp.Type = 'Prospect Locally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = STREET_STAGENAME;
//setting shiping date/close date
//opp.CloseDate = system.today() + 70;
}
else if (leadRecordType.Name == 'street') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Locally_Managed__c;
//Updated by ADUA for SFS-1114
opp.Type = 'Prospect Locally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = STREET_STAGENAME;
opp.CloseDate = system.today() + 70;
}
else if (leadRecordType.Name == 'National') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Nationally_Managed__c;
//Updated by ADUA for SFS-1114
opp.Type = 'Prospect Nationally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = NATIONAL_STAGENAME;
}
opp.RecordTypeId = oppRecordTypeId;
}
//opp.Type = CS_UtilConstants__c.getInstance(OPPTY_TYPE_CONVERTEDLEAD).Value__c;
opp.Amount = myLead.Total_Weekly_Potential__c;
//opp.Probability = Decimal.valueOf(1);
//Updated by ADUA for SFS-1547 as 'Working' as stageName was not part of National Prospect - Sales Prcoess
//opp.StageName = CS_UtilConstants__c.getInstance(WORKING).Value__c;
opp.Source__c = myLead.LeadSource;
Database.update(opp);
system.debug('Final StageName = ' + opp.StageName);
}
I need to cover the LeadRecordType.Name == 'ChefStore' and LeadRecordType.Name == 'National' part
This is the main class code
if (oppID != null) {
Opportunity opp = [select id, RecordTypeId, StageName from opportunity where id = :oppID];
system.debug('Initial StageName = ' + opp.StageName);
//get the oppty "Prospect - Locally Manager" Record type id from custom settings
if (recordTypeId != null) {
//Updated by ADUA to have different record types for Opportunity from Converted leads as per Lead Record Type
String oppRecordTypeId;
if (leadRecordType.Name == 'ChefStore') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Locally_Managed__c;
opp.Type = 'Prospect Locally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = STREET_STAGENAME;
//setting shiping date/close date
//opp.CloseDate = system.today() + 70;
}
else if (leadRecordType.Name == 'street') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Locally_Managed__c;
//Updated by ADUA for SFS-1114
opp.Type = 'Prospect Locally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = STREET_STAGENAME;
opp.CloseDate = system.today() + 70;
}
else if (leadRecordType.Name == 'National') {
oppRecordTypeId = recordTypeId.RecordType_Prospect_Nationally_Managed__c;
//Updated by ADUA for SFS-1114
opp.Type = 'Prospect Nationally Managed';
//Updated by ADUA for SFS-1547
// SSDR23-321 Prospect Locally Managed Opptys Probability is displaying wrong(%) if there is no stage selected.
opp.StageName = NATIONAL_STAGENAME;
}
opp.RecordTypeId = oppRecordTypeId;
}
//opp.Type = CS_UtilConstants__c.getInstance(OPPTY_TYPE_CONVERTEDLEAD).Value__c;
opp.Amount = myLead.Total_Weekly_Potential__c;
//opp.Probability = Decimal.valueOf(1);
//Updated by ADUA for SFS-1547 as 'Working' as stageName was not part of National Prospect - Sales Prcoess
//opp.StageName = CS_UtilConstants__c.getInstance(WORKING).Value__c;
opp.Source__c = myLead.LeadSource;
Database.update(opp);
system.debug('Final StageName = ' + opp.StageName);
}
I need to cover the LeadRecordType.Name == 'ChefStore' and LeadRecordType.Name == 'National' part
- newbiewithapex
- February 07, 2019
- Like
- 0
How to solve "method does not exist or incorrect signature" error?
Hi I am trying to run the test and getting " Method does not exist or incorrect signature: void sortList(List<Opportunity>, String, String) from the type superSortTest (Line: 12, Column: 9)" error. Can someone please help me fix the error?
//Main Class
public class superSort {
public static void sortList(List<sObject> items, String sortField, String order){
Boolean isSortFieldReference = false;
Map<Id,String> referenceName;
if(items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getType().Name() == 'REFERENCE'){
isSortFieldReference = true;
referenceName = new Map<Id,String>();
Set<Id> referenceIds = new Set<Id>();
for(sObject s : items){
referenceIds.add((Id)s.get(sortField));
}
String objectID = (String)items[0].get(sortField);
String prefix = objectID.substring(0,3);
String objectType;
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
for(Schema.SObjectType s : gd.values()){
if(prefix == s.getDescribe().getKeyPrefix()){
objectType = s.getDescribe().Name;
}
}
String queryString = 'select Id, Name from ' + objectType + ' where ID IN :referenceIDs';
for(sObject s : Database.query(queryString )){
referenceName.put((Id)s.get('Id'),(String)s.get('Name'));
}
}
List<cObject> resultList = new List<cObject>();
Map<object, List<cObject>> objectMap = new Map<object, List<cObject>>();
for(sObject ob : items){
if(isSortFieldReference == false){
if(objectMap.get(ob.get(sortField)) == null){
objectMap.put(ob.get(sortField), new List<cObject>());
}
cObject o = new cObject(ob);
objectMap.get(ob.get(sortField)).add(o);
}else{
if(objectMap.get(referenceName.get((Id)ob.get(sortField))) == null){
objectMap.put(referenceName.get((Id)ob.get(sortField)), new List<cObject>());
}
cObject o = new cObject(ob);
objectMap.get(referenceName.get((Id)ob.get(sortField))).add(o);
}
}
List<object> keys = new List<object>(objectMap.keySet());
keys.sort();
for(object key : keys){
resultList.addAll(objectMap.get(key));
}
items.clear();
if(order.toLowerCase() == 'asc'){
for(cObject ob : resultList){
items.add(ob.obj);
}
}else if(order.toLowerCase() == 'desc'){
for(integer i = resultList.size()-1; i >= 0; i--){
items.add(resultList[i].obj);
}
}
}
public class cObject{
sObject obj {get; set;}
public cObject(sObject obj){
this.obj = obj;
}
}
}
//Test Class
@isTest
public class superSortTest {
public static testMethod void sortAscendingTest(){
List<Opportunity> opps = new List<Opportunity>();
for(integer i = 0; i<1000; i++){
opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
}
Test.startTest();
Long start = system.currentTimeMillis();
sortList(opps,'Amount','asc');
system.debug(system.currentTimeMillis() - start);
Test.stopTest();
//Assert the list was sorted correctly
Decimal assertValue = -1;
for(Opportunity o : opps) {
System.debug('Opp value: ' + o.amount);
System.assert(assertValue <= o.amount);
assertValue = o.amount;
}
}
public static testMethod void sortDescendingTest(){
List<Opportunity> opps = new List<Opportunity>();
for(integer i = 0; i<1000; i++){
opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
}
Test.startTest();
sortList(opps,'Amount','desc');
Test.stopTest();
//Assert the list was sorted correctly
Decimal assertValue = 1001;
for(Opportunity o : opps) {
System.debug('Opp value: ' + o.amount);
System.assert(assertValue >= o.amount);
assertValue = o.amount;
}
}
}
//Main Class
public class superSort {
public static void sortList(List<sObject> items, String sortField, String order){
Boolean isSortFieldReference = false;
Map<Id,String> referenceName;
if(items[0].getSObjectType().getDescribe().fields.getMap().get(sortField).getDescribe().getType().Name() == 'REFERENCE'){
isSortFieldReference = true;
referenceName = new Map<Id,String>();
Set<Id> referenceIds = new Set<Id>();
for(sObject s : items){
referenceIds.add((Id)s.get(sortField));
}
String objectID = (String)items[0].get(sortField);
String prefix = objectID.substring(0,3);
String objectType;
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
for(Schema.SObjectType s : gd.values()){
if(prefix == s.getDescribe().getKeyPrefix()){
objectType = s.getDescribe().Name;
}
}
String queryString = 'select Id, Name from ' + objectType + ' where ID IN :referenceIDs';
for(sObject s : Database.query(queryString )){
referenceName.put((Id)s.get('Id'),(String)s.get('Name'));
}
}
List<cObject> resultList = new List<cObject>();
Map<object, List<cObject>> objectMap = new Map<object, List<cObject>>();
for(sObject ob : items){
if(isSortFieldReference == false){
if(objectMap.get(ob.get(sortField)) == null){
objectMap.put(ob.get(sortField), new List<cObject>());
}
cObject o = new cObject(ob);
objectMap.get(ob.get(sortField)).add(o);
}else{
if(objectMap.get(referenceName.get((Id)ob.get(sortField))) == null){
objectMap.put(referenceName.get((Id)ob.get(sortField)), new List<cObject>());
}
cObject o = new cObject(ob);
objectMap.get(referenceName.get((Id)ob.get(sortField))).add(o);
}
}
List<object> keys = new List<object>(objectMap.keySet());
keys.sort();
for(object key : keys){
resultList.addAll(objectMap.get(key));
}
items.clear();
if(order.toLowerCase() == 'asc'){
for(cObject ob : resultList){
items.add(ob.obj);
}
}else if(order.toLowerCase() == 'desc'){
for(integer i = resultList.size()-1; i >= 0; i--){
items.add(resultList[i].obj);
}
}
}
public class cObject{
sObject obj {get; set;}
public cObject(sObject obj){
this.obj = obj;
}
}
}
//Test Class
@isTest
public class superSortTest {
public static testMethod void sortAscendingTest(){
List<Opportunity> opps = new List<Opportunity>();
for(integer i = 0; i<1000; i++){
opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
}
Test.startTest();
Long start = system.currentTimeMillis();
sortList(opps,'Amount','asc');
system.debug(system.currentTimeMillis() - start);
Test.stopTest();
//Assert the list was sorted correctly
Decimal assertValue = -1;
for(Opportunity o : opps) {
System.debug('Opp value: ' + o.amount);
System.assert(assertValue <= o.amount);
assertValue = o.amount;
}
}
public static testMethod void sortDescendingTest(){
List<Opportunity> opps = new List<Opportunity>();
for(integer i = 0; i<1000; i++){
opps.add(new Opportunity(Name = 'test' + i, Amount = 1000 * Math.random()));
}
Test.startTest();
sortList(opps,'Amount','desc');
Test.stopTest();
//Assert the list was sorted correctly
Decimal assertValue = 1001;
for(Opportunity o : opps) {
System.debug('Opp value: ' + o.amount);
System.assert(assertValue >= o.amount);
assertValue = o.amount;
}
}
}
- newbiewithapex
- February 04, 2019
- Like
- 0
how to solve Attempt to de-reference a null object error?
Can someone please help me fix the "Attempt to de-reference a null object" error for this method below. I am getting error on 3rd line"testClass.updateStatusNew(null, null);"
static testMethod void testupdateStatusNew(){ TaskHandler testClass = new TaskHandler(); testClass.updateStatusNew(null, null); List<Account> acclstnew = new List<Account>(); List<Opportunity> opplstnew = new List<Opportunity>(); Set<Id> TestcbrIds = new Set<Id>(); Map<Id,CBR__c> TestcbrMap = new Map<Id,CBR__c>(); List<CBR__c> cbrtoConvertList = new List<CBR__c>(); String aggignedCBRrecId = Schema.SObjectType.CBR__c.RecordTypeInfosByName.get('Assigned CBR').RecordTypeId; Account acc = UTIL_TestDataCreation.createSingleAccount('TestAccountName', thisUser.Id); acc.Account_Class__c = 'Ship To'; testCBR.Tandem_Account_Name__c= acc.Id; testCBR.CBR_Due_Date__c = System.today(); testCBR.CBR_Assigned_By__c = thisUser.Id; testCBR.CBR_Assigned_Date__c = System.Today(); testCBR.Risk_Level__c = ''; testCBR.CBR_Owner__c = thisUser.Id; testCBR.CBR_Status__c = 'Assigned'; testCBR.RecordTypeId = null; TestcbrIds.add(testCBR.Tandem_Account_Name__c); TestcbrMap.put(testCBR.Tandem_Account_Name__c,testCBR); cbrtoConvertList.add(testCBR); Database.insert(testCBR,true); Contact conObj = UTIL_TestDataCreation.createContact('Aron','David', true); test.startTest(); testClass.updateStatusNew(TestcbrIds,TestcbrMap); test.stopTest(); }
- newbiewithapex
- February 21, 2019
- Like
- 0
Send emails test class
I have this method that send emails to event invitees on event update. I am trying to cover few missing lines but I can't seem to figure it out how. Can someone please take a look and help me out?
public static void sendEmailPostEventUpdate(Event updatedEvent){ List<EventRelation> eveRels = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :updatedEvent.Id ORDER BY Relation.Name ASC]; System.debug('eveRels' + eveRels); List<Id> leadRecptList = new List<Id>(); List<Id> userRecptList = new List<Id>(); List<Id> contactRecptList = new List<Id>(); for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } System.debug('Initiating emailSending...'); sendEmail(leadRecptList,userRecptList,contactRecptList,updatedEvent); }
- newbiewithapex
- February 21, 2019
- Like
- 0
How to write test class for the method that take user back?
I have method that used to go back by clicking cancel button. Can someone help me figure out test class for this method?
public pageReference back() { pageReference pf; if (ApexPages.currentPage().getParameters().get('Id') != null) { pf = new pageReference('/' + ApexPages.currentPage().getParameters().get('Id')); } return pf; }
- newbiewithapex
- February 20, 2019
- Like
- 0
how to write test class for method that fetches recommendations?
Below method fetch recommendations and I am not sure how to write test class for this method. Can someone please help me with this?
@AuraEnabled public static string getRecommendations(string recId) { string errorMessage; Recommendation__c rec = new Recommendation__c(); rec = [select Id, Name, Account__c, Account__r.Name, Account__r.RecordTypeId, Sub_Type__c, Opportunity__c, Description__c, Record_Type_Name__c from Recommendation__c where Id = :recId limit 1]; if (String.IsNOTBlank(rec.Opportunity__c)) { AuraHandledException e = new AuraHandledException(CS_UtilConstants__c.getValues('OPPTY_EXISTS_RECOMMENDATIONS_INFO').Value__c); e.setMessage(CS_UtilConstants__c.getValues('OPPTY_EXISTS_RECOMMENDATIONS_INFO').Value__c); throw e; } else if (rec.Record_Type_Name__c == CS_UtilConstants__c.getInstance('CONVERSION').Value__c && (rec.Description__c == Null || rec.Description__c == '') && (rec.Sub_Type__c == Null || rec.Sub_Type__c == '')) { AuraHandledException e = new AuraHandledException(CS_UtilConstants__c.getValues('CONVERSION ERROR MESSAGE').Value__c); e.setMessage(CS_UtilConstants__c.getValues('CONVERSION ERROR MESSAGE').Value__c); throw e; } return null; }
- newbiewithapex
- February 20, 2019
- Like
- 0
Code coverage dropped
public without sharing class EventInviteesCntrl { @AuraEnabled public List<EventRelation> invitees = new List<EventRelation>(); @AuraEnabled public List<String> accountCompanyDtls = new List<String>(); @AuraEnabled public List<boolean> redLeadsWithoutEmail = new List<boolean>(); @AuraEnabled public static List<EventRelation> getEventInvitees(String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Id recordId = (Id)eventId; String sObjectUsed = recordId.getSObjectType().getDescribe().getName(); if(sObjectUsed.equalsIgnoreCase('Event')){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId ORDER BY Relation.Name ASC LIMIT 5]; } else{ Event cbrEvent = [SELECT Id, CBR__c FROM Event WHERE CBR__c = :eventId LIMIT 1]; if(cbrEvent!=null){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :cbrEvent.Id ORDER BY Relation.Name ASC LIMIT 5]; } } return inviteesList; } @AuraEnabled public static List<EventRelation> getAllEventInvitees(String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Id recordId = (Id)eventId; String sObjectUsed = recordId.getSObjectType().getDescribe().getName(); if(sObjectUsed.equalsIgnoreCase('Event')){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId ORDER BY Relation.Name ASC]; } else { Event cbrEvent = [SELECT Id, CBR__c FROM Event WHERE CBR__c = :eventId LIMIT 1]; if(cbrEvent!=null){ inviteesList = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :cbrEvent.Id ORDER BY Relation.Name ASC]; } } return inviteesList; } @AuraEnabled public static Integer getTotalEventInvitees (String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); inviteesList = getAllEventInvitees(eventId); return inviteesList.size(); } @AuraEnabled public static String getApproxEventInvitees (String eventId) { List<EventRelation> inviteesList = new List<EventRelation>(); Integer size = getTotalEventInvitees(eventId); if(size > 3){ return ('3+'); } else{ return(String.valueOf(size)); } } @AuraEnabled public static EventInviteesCntrl getInviteesDtls (String eventId) { System.debug('get invitees dtls -->'+eventId); EventInviteesCntrl obj = new EventInviteesCntrl(); obj.invitees = getAllEventInvitees(eventId); obj.redLeadsWithoutEmail = initListBool(obj.invitees.size()); Integer counter = 0; for(EventRelation eveRel : obj.invitees){ if(eveRel.Relation.Type == 'Contact'){ Contact con = [select id, Account.Name, email from Contact where id = :eveRel.RelationId]; if(con.email == null || con.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } obj.accountCompanyDtls.add(con.Account.Name); } else if(eveRel.Relation.Type == 'Lead'){ Lead lead = [select id, email, Company from Lead where id = :eveRel.RelationId]; if(lead.email == null || lead.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } obj.accountCompanyDtls.add(lead.Company); } else if(eveRel.Relation.Type == 'User'){ User user = [select id, CompanyName, email from User where id = :eveRel.RelationId]; if(user.email == null || user.email == ''){ obj.redLeadsWithoutEmail.set(counter, true); } if(user.CompanyName!=null && user.CompanyName!=''){ obj.accountCompanyDtls.add(user.CompanyName); } else{ obj.accountCompanyDtls.add('US Foods'); } } counter++; } return obj; } @AuraEnabled public static void mRemoveInvitee(String removedEveRelID) { EventRelation deletingEveRel = [Select id, RelationId from EventRelation where id= :removedEveRelID]; Database.delete(deletingEveRel); } @AuraEnabled public static UnsavedSelectedInvitee[] mPostAdditionOfInvitees(List<String> selectedInviteesIDs) { List<UnsavedSelectedInvitee> unsavedSelectedInvitees = new List<UnsavedSelectedInvitee>(); for(String sObjID : selectedInviteesIDs){ String sObjAPIName = (Id.valueOf(sObjID)).getSObjectType().getDescribe().getName(); if(sObjAPIName.equalsIgnoreCase('Contact')){ Contact con = [SELECT id,name,Account.Name, email from Contact where id= :sObjID]; if(con.email == null || con.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), con.Name, con.Account.Name, 'Contact',true)); } else { unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), con.Name, con.Account.Name, 'Contact')); } } else if(sObjAPIName.equalsIgnoreCase('User')){ User user = [SELECT id,Name,CompanyName, email from User where id= :sObjID]; if(user.CompanyName!=null && user.CompanyName!=''){ if(user.email == null || user.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, user.CompanyName, 'User', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, user.CompanyName, 'User')); } } else{ if(user.email == null || user.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, 'US Foods', 'User', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), user.Name, 'US Foods', 'User')); } } } else if(sObjAPIName.equalsIgnoreCase('Lead')){ Lead lead = [SELECT id,name,Company,email from Lead where id= :sObjID]; if(lead.email == null || lead.email == ''){ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), lead.Name, lead.Company, 'Lead', true)); } else{ unsavedSelectedInvitees.add(new UnsavedSelectedInvitee(Id.valueOf(sObjID), lead.Name, lead.Company, 'Lead')); } } } return unsavedSelectedInvitees; } @AuraEnabled public static List<EventTracker> checkUserAvailability (DateTime currEventStart, List<String> inviteeIDs) { System.debug('Event start -->'+currEventStart); List<EventTracker> eventsTrack = new List<EventTracker>(); List<boolean> slotsBooked; if(currEventStart == null){ currEventStart = System.now(); } DateTime conditional_start = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(06,00,00,000)); DateTime conditional_end = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(23,00,00,000)); DateTime conditional_starts = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(00,00,00,000)); DateTime conditional_ends = DateTime.newInstanceGmt(currEventStart.date(), Time.newInstance(23,00,00,000)); for(String invitee : inviteeIDs){ System.debug('Invitees -->'+invitee); slotsBooked = initListBool(72); List<Id> todayEvents = new List<Id>(); for (Event tdEvt : [Select Id FROM Event Where StartDateTime >= :conditional_start AND EndDateTime <= :conditional_end ORDER BY StartDateTime LIMIT 10000]) { todayEvents.add(tdEvt.Id); } System.debug('todayEvents'+todayEvents); List<Id> userInvites = new List<Id>(); for (EventRelation evtInv : [SELECT EventId FROM EventRelation WHERE RelationId = :invitee AND EventId IN :todayEvents]){ userInvites.add(evtInv.EventId); } system.debug('todays events where they are an invitee-->' + userInvites); System.debug('Event '); List<Event> userEvents = [SELECT Id, OwnerID, Owner.Name, Subject, ActivityDateTime, ActivityDate, DurationInMinutes, StartDateTime, EndDateTime, Description, WhatID, What.Name, WhoID, Who.Name, isAllDayEvent FROM Event where (CreatedById = :invitee and StartDateTime >= :conditional_start and EndDateTime <= :conditional_end) OR ID IN :userInvites OR (CreatedById = :invitee and StartDateTime >= :conditional_starts and EndDateTime <= :conditional_ends)]; System.debug('User Events-->'+userEvents); for(Event usrEve : userEvents){ Integer index = (usrEve.StartDateTime.hour() - 6) *4; DateTime counterDt = usrEve.StartDateTime; boolean isLastQuarter = false; if(usrEve.DurationInMinutes >= 1440) { for(Integer i=0; i<slotsBooked.size();i++){ slotsBooked.set(i,true); } } else { for(Integer i=0; i<usrEve.DurationInMinutes; ){ if(index >= 0){ if(counterDt.minute()>=0 && counterDt.minute()<15){ if(!isLastQuarter){ slotsBooked.set(index+0, true); } else if(isLastQuarter && index > 0){ slotsBooked.set(index-1, true); } } if(counterDt.minute()>= 15 && counterDt.minute()<30){ slotsBooked.set(index+1, true); if(isLastQuarter){ slotsBooked.set(index, true); } } if(counterDt.minute()>= 30 && counterDt.minute()<45){ slotsBooked.set(index+2, true); } if(counterDt.minute()>= 45){ slotsBooked.set(index+3, true); } } System.debug('Counter Date : '+counterDt+' ,Index Position : '+index+' ,i : '+i); counterDt = counterDt.addMinutes(15); if(counterDt.minute()==0){ isLastQuarter = true; } index = (counterDt.hour() - 6) *4; i+=15; } } } eventsTrack.add(new EventTracker(Id.valueOf(invitee), slotsBooked)); System.debug('SlotsBooked-->'+slotsBooked); } return eventsTrack; } @AuraEnabled public static void saveInvitees (boolean saveAllEvents, String eventId, String inviteesJson) { String eventIdToMap = eventId;//added by Nimitha for defect 583. List<Id> userInvitees = new List<Id>(); if(eventId!=null && inviteesJson!=null && eventId!='' && inviteesJson!=''){ Event eve = [SELECT id, subject, isRecurrence, StartDateTime, EndDateTime, location, RecurrenceActivityId, isAllDayEvent, Frequency_Details__c FROM Event WHERE id= :eventId LIMIT 1]; List<UnsavedSelectedInvitee> inviteesList = (List<UnsavedSelectedInvitee>)JSON.deserialize(inviteesJson, List<UnsavedSelectedInvitee>.class); List<EventRelation> eventRelations = new List<EventRelation>(); if(saveAllEvents!=null && saveAllEvents==true){ eventId = eve.RecurrenceActivityId; } for(UnsavedSelectedInvitee invitee : inviteesList){ EventRelation eveRel = new EventRelation(); eveRel.RelationId = invitee.sObjID; if(String.isBlank(eventId)){ eveRel.eventId = eventIdToMap; }else{ eveRel.eventId = eventId; } eventRelations.add(eveRel); if(invitee.sObjID.getSObjectType().getDescribe().getName() == 'User'){ userInvitees.add(invitee.sObjID); } } if(!eventRelations.isEmpty()){ Database.DMLOptions dlo = new Database.DMLOptions(); dlo.EmailHeader.triggerUserEmail = false; dlo.EmailHeader.triggerOtherEmail = true; Database.insert(eventRelations, dlo); System.debug('Sending email...'); sendEmail(userInvitees, eve); } } else{ throw new AuraHandledException('Looks like some Exception has occured, kindly try again'); } } @AuraEnabled public static void saveInviteesDirectly (string eventId, List<String> addedInviteesId) { addedInviteesId.remove(0); List<Id> userInvitees = new List<Id>(); if(eventId!=null && eventId!='' && !addedInviteesId.isEmpty()){ Event eve = [SELECT id, subject, StartDateTime, EndDateTime, location, isAllDayEvent, IsRecurrence, Frequency_Details__c FROM Event WHERE id= :eventId LIMIT 1]; List<EventRelation> eventRelations = new List<EventRelation>(); for(String invitee : addedInviteesId){ if(invitee != null && invitee!=''){ EventRelation eveRel = new EventRelation(); eveRel.RelationId = invitee; eveRel.eventId = eventId; eventRelations.add(eveRel); if((Id.valueOf(invitee)).getSObjectType().getDescribe().getName() == 'User'){ userInvitees.add(Id.valueOf(invitee)); } } } if(!eventRelations.isEmpty()){ Database.DMLOptions dlo = new Database.DMLOptions(); dlo.EmailHeader.triggerUserEmail = false;dlo.EmailHeader.triggerOtherEmail = true; Database.insert(eventRelations, dlo); sendEmail(userInvitees, eve); } } else{ throw new AuraHandledException('Looks like some Exception has occured, kindly try again'); } } @AuraEnabled public static List<String> getTimes (DateTime startDateTime, DateTime endDateTime) { List<String> times = new List<String>(); String str0; String str1; String str2; if(startDateTime==null||endDateTime==null){ startDateTime = System.now(); endDateTime = System.now(); } String startDt = startDateTime.format('yyyy-MM-dd hh:mm a'); String endDt = endDateTime.format('yyyy-MM-dd hh:mm a'); str0 = String.valueOf(startDateTime.format('MMM dd, yyyy')); if(startDt.contains('AM')){ str1 = (startDateTime.hour()==0 ? 12 : startDateTime.hour()) + ':'+startDateTime.minute() + ' AM'; if(startDateTime.minute() < 10){ str1 = (startDateTime.hour()==0 ? 12 : startDateTime.hour()) + ':'+startDateTime.minute() + '0 AM'; } } else if(startDt.contains('PM')){ str1 = (startDateTime.hour()==12 ? startDateTime.hour() : (startDateTime.hour()-12)) + ':'+startDateTime.minute() + ' PM'; if(startDateTime.minute() < 10){ str1 = (startDateTime.hour()==12 ? startDateTime.hour() : (startDateTime.hour()-12)) + ':'+startDateTime.minute() + '0 PM'; } } if(startDateTime.day() == endDateTime.day()){ if(endDt.contains('AM')){ str2 = (endDateTime.hour()==0 ? 12 : endDateTime.hour()) + ':'+endDateTime.minute() + ' AM'; if(endDateTime.minute() < 10){ str2 = (endDateTime.hour()==0 ? 12 : endDateTime.hour()) + ':'+endDateTime.minute() + '0 AM'; } } else if(endDt.contains('PM')){ str2 = (endDateTime.hour()==12 ? endDateTime.hour() : (endDateTime.hour()-12)) + ':'+endDateTime.minute() + ' PM'; if(endDateTime.minute() < 10){ str2 = (endDateTime.hour()==12 ? endDateTime.hour() : (endDateTime.hour()-12)) + ':'+endDateTime.minute() + '0 PM'; } } } else{ str2 = '11:59 PM';} times.add(str0); times.add(str1); times.add(str2); return times; } @AuraEnabled public static boolean validateInternalUserIfInvited(String eventId) { List<EventRelation> eveRelList = getAllEventInvitees(eventId); for(EventRelation eveRel : eveRelList){ if(eveRel.RelationId == UserInfo.getUserId()){//checking if LoggedIn User is invited return true; } } return false; } @AuraEnabled public static void processUserInviteeResponse(String eventId, boolean isAccepted){ EventRelation eveRel = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate FROM EventRelation WHERE eventId = :eventId AND RelationId = :UserInfo.getUserId() limit 1]; if(isAccepted){ eveRel.Status = 'Accepted'; eveRel.RespondedDate = System.now(); } else if(!isAccepted){ eveRel.Status = 'Declined'; eveRel.RespondedDate = System.now(); } Database.update(eveRel); } public static void sendEmail(List<Id> userInvitees, Event currEvent) { List<Messaging.SingleEmailMessage> emailList = new List<Messaging.SingleEmailMessage>(); String eventRedirectURL = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + currEvent.Id; for(Id inviteeId : userInvitees){ Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); User user = [SELECT Id, TimeZoneSidKey FROM User WHERE Id=:inviteeId]; String eventRedirectURL_accept = System.URL.getSalesforceBaseUrl().toExternalForm() + '/c/ResponseMgmt.app?eventId='+currEvent.Id+'&userId='+inviteeId+'&response=Accepted'; String eventRedirectURL_decline = System.URL.getSalesforceBaseUrl().toExternalForm() + '/c/ResponseMgmt.app?eventId='+currEvent.Id+'&userId='+inviteeId+'&response=Declined'; List<String> displayUserTime = getTimes(currEvent.StartDateTime, currEvent.EndDateTime, user.TimeZoneSidKey, currEvent.IsAllDayEvent); email.setTargetObjectId(inviteeId); if(currEvent.isRecurrence){ email.setSubject('Recurring Event Invitation : '+currEvent.Subject); } else{ email.setSubject('Meeting Request : '+currEvent.Subject); } if(currEvent.IsAllDayEvent){ if(currEvent.isRecurrence){ email.setHTMLBody(' <b>Recurring Event Invitation</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+currEvent.Frequency_Details__c+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } else{ email.setHTMLBody(' <b>Meeting Request</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+displayUserTime.get(0)+' '+displayUserTime.get(1)+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } } else{ if(currEvent.IsRecurrence){ email.setHTMLBody(' <b>Recurring Event Invitation</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+currEvent.Frequency_Details__c+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } else{ email.setHTMLBody(' <b>Meeting Request</b><br/><hr/><br/><br/>'+ ' <b>Subject</b> '+currEvent.Subject+'<br/>'+ ' <b>When</b> '+displayUserTime.get(0)+' '+displayUserTime.get(1)+' - '+displayUserTime.get(2)+' '+getTimeZoneValue(user.TimeZoneSidKey)+'<br/>'+ ' <b>Where</b> '+(currEvent.Location==null? '': currEvent.Location)+'<br/><br/>'+ '<center><a href="'+eventRedirectURL_accept+'"><button type="button" value=" Accept " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Accept</button></a> '+ '<a href="'+eventRedirectURL_decline+'"><button type="button" value=" Decline " style="background-color:#0087b5;border:2px solid white;color:white;font-size:12px;padding:5px 15px">Decline</button></a>'+ '</center><br/>'+ '<center>or click <a href="'+eventRedirectURL+'">'+eventRedirectURL+'</a></center>'); } } email.setSaveAsActivity(false); emailList.add(email); } Messaging.sendEmail(emailList,false); } public static List<String> getTimes (DateTime startDateTime, DateTime endDateTime, String timeZone, boolean isAllDayEvent) { System.debug('####StartDate before Formatting - '+startDateTime); List<String> times = new List<String>(); String str0; String str1; String str2; if(startDateTime==null||endDateTime==null){ startDateTime = System.now(); endDateTime = System.now(); } if(timeZone==null||timeZone==''){ timeZone = 'GMT'; } if(!isAllDayEvent){ String startDt = startDateTime.format('MM/dd/yyyy hh:mm a', timeZone); String endDt = endDateTime.format('MM/dd/yyyy hh:mm a', timeZone); List<String> startDtItems = startDt.split(' '); List<String> endDtItems = endDt.split(' '); str0 = startDtItems.get(0); System.debug('####StartDate after Formatting - '+str0); str1 = startDtItems.get(1) + ' ' + startDtItems.get(2); str2 = endDtItems.get(1) + ' ' + endDtItems.get(2); } else if(isAllDayEvent){ DateTime startDt_mod = startDateTime.addHours(12); str0 = startDt_mod.format('MM/dd/yyyy', timeZone); str1 = 'All-Day Event'; } times.add(str0); times.add(str1); times.add(str2); return times; } public static String getTimeZoneValue(String timeZone) { List<String> tzLabel; String returnStr=''; Schema.DescribeFieldResult fieldResult = User.TimeZoneSidKey.getdescribe(); List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues(); for(Schema.PicklistEntry p : ple) { if(p.getValue().equals(timeZone)){ tzLabel = p.getlabel().split(' '); for(Integer i=0; i<tzLabel.size(); i++) { if(i==0 || i==tzLabel.size()-1){ continue; } else{ returnStr += tzLabel.get(i)+' '; } } return returnStr; } } return 'GMT'; } public static List<boolean> initListBool(Integer size){ List<boolean> boolList = new List<boolean>(); for(Integer i=0; i<size; i++){ boolList.add(false); } System.debug('SlotsInit-->'+boolList); return boolList; } public class UnsavedSelectedInvitee{ @AuraEnabled public Id sObjID {get; set;} @AuraEnabled public String inviteeName {get; set;} @AuraEnabled public String accountCompany {get; set;} @AuraEnabled public String inviteeType {get; set;} @AuraEnabled public boolean isLeadWithoutEmail {get; set;} public UnsavedSelectedInvitee(Id sObjID, String inviteeName, String accountCompany, String inviteeType){ this.sObjID = sObjID; this.inviteeName = inviteeName; this.accountCompany = accountCompany; this.inviteeType = inviteeType; this.isLeadWithoutEmail = false; } public UnsavedSelectedInvitee(Id sObjID, String inviteeName, String accountCompany, String inviteeType, boolean isLeadWithoutEmail){ this.sObjID = sObjID; this.inviteeName = inviteeName; this.accountCompany = accountCompany; this.inviteeType = inviteeType; this.isLeadWithoutEmail = isLeadWithoutEmail; } } class EventTracker{ @AuraEnabled public Id inviteeID {get; set;} @AuraEnabled public List<boolean> isCurrentSlotBooked {get; set;} public EventTracker(Id inviteeID, List<boolean> isCurrentSlotBooked){ this.inviteeID = inviteeID; this.isCurrentSlotBooked = isCurrentSlotBooked; } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class method to cover If loop?
I am trying cover if loop from EventHandler class but I can't figurer out why this part of the code is not covered. Test class is way too long to post it here so can someone please help me with this?
if(eveRels !=null && eveRels.size()>0){ for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I cover if and for loop from EventHandler class from test class?
I have this EventHandler class that I am trying to increse code coverage. I need help figuring out how to handle this if loop.
if(eveRels !=null && eveRels.size()>0){ for(EventRelation eveRel : eveRels){ if(!test.isRunningTest()) { if(eveRel.Relation.type.equals('User')){ userRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Lead')){ leadRecptList.add(eveRel.RelationId); } if(eveRel.Relation.type.equals('Contact')){ contactRecptList.add(eveRel.RelationId); } } else { if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){ userRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){ leadRecptList.add(eveRel.RelationId); } if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){ contactRecptList.add(eveRel.RelationId); } } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class method to cover If loop from EventHandler class?
I have the test class that is covering most of the EventHandler class but just missing this if loop coverage. Unfortunatly both classes are too big to post here. Can someone help me with this please?
if (Limits.getQueries() < Limits.getLimitQueries() && !eventOwnerIdSet.isEmpty()) { if (userMap == null) { userMap = new Map<Id, User> ([select Id, Sales_Coordinator__c, ProfileId from User]); } for (Event e: scEventList) { if (string.isNOTblank(userMap.get(e.ownerId).Sales_Coordinator__c)) { // current event owner must have an SC if (e.IsRecurrence ) { // if recurring event series e.ownerId = userMap.get(e.ownerId).Sales_Coordinator__c; System.debug('EventId1' +e.Id); processedRecEventIds.add(e.Id); // add series parent id to avoid processing the child records } else if (e.RecurrenceActivityId != null && !e.IsRecurrence) { // if recurring event child System.debug('EventId' +e.Id); Event parentEvt = [Select id, ownerId, whoId, isRecurrence from Event where id= :e.RecurrenceActivityId and isRecurrence=true]; //parentEvt.ownerId = userMap.get(parentEvt.ownerId).Sales_Coordinator__c; //update parentEvt; system.debug('####New Owner - '+parentEvt.ownerId); processedRecEventIds.add(parentEvt.id); } } else if ((e.IsRecurrence || !processedRecEventIds.contains(e.RecurrenceActivityId) || String.isBlank(e.RecurrenceActivityId)) && userMap.get(memberIdSCIdMap.get(e.Bulk_Item_Indicator__c)).ProfileId != SalesforceIds__c.getOrgDefaults().Profile_USF_SalesCoordinator__c){ } } }
- newbiewithapex
- February 19, 2019
- Like
- 0
How do I write test class for this class?
I need to write test class for the below class. How do I do that?
public class DataUtil{ private static final String am_time = 'AM'; private static final String empty_Space = ' '; private static final String split_Time = '\\:'; private static final string number_Twelve = '12'; public static Map<Id, Account> populateAccountData(Set<Id> idsSet) { Map<Id,Account> accountDataMap = new Map<Id,Account>(); Map<String, String> sObjAndAccFld = new Map<String, String>(); Map<String, Set<Id>> sObjAndIdsMap = new Map<String, Set<Id>>(); Map<id,Set<id>> ridAndAccIDMap = new Map<id,Set<id>>(); Set<Id> accountIdsSet = new Set<Id>(); for(Id recId: idsSet) {//Iteraing the all Related Ids system.debug('SSSSSSS : '+String.valueOf(recId.getSobjectType())); String sObjName = String.valueOf(recId.getSobjectType()); if(sObjAndIdsMap.containsKey(sObjName)) { // checking and adding the related id to the appropriate sObject sObjAndIdsMap.get(sObjName).add(recId); } else { Set<Id> idst = new Set<Id> {recId}; sObjAndIdsMap.put(sObjName,idst); } if(sObjName == 'Account') { //If related Id is ACCOUNT Id then add it to the accountIdsSet accountIdsSet.add(recId); Set<Id> ridSet = new Set<Id> {recId}; ridAndAccIDMap.put(recId,ridSet); } else {//If related Id is NOT ACCOUNT Id then finding the Id related to which object List<Schema.DescribeSObjectResult> describeObj = Schema.describeSObjects(new String[]{sObjName}); Map<String, Schema.SObjectField> FsMap = describeObj[0].fields.getMap(); for (Schema.SObjectField objField: FsMap.values()) { Schema.DescribeFieldResult fieldDesc = objField.getDescribe(); List<Schema.sObjectType> referenceObj = fieldDesc.getReferenceTo(); if(!referenceObj.isEmpty()){ // determine if field is a lookup field if(referenceObj[0].getDescribe() == Schema.SObjectType.Account){ // determine if field is a lookup to Account object String acctFieldName = fieldDesc.getName(); // get field API name of the account lookup field sObjAndAccFld.put(sObjName, acctFieldName); break; } } } } } for(String objName : sObjAndAccFld.keySet()) {// Building Dynamic quesy and Ferching the Account Id based on the relaed object Set<Id> recIds = sObjAndIdsMap.get(objName); String fieldAPIName = sObjAndAccFld.get(objName); string soql = 'select id, '+fieldAPIName+' from '+objName+' where id IN: recIds'; system.debug('QQQQQuery : '+soql); for(sObject sObj: database.query(soql)) { //added new condition on 5/3 to check if account is null refer D 1159 if(sObj.get(fieldAPIName) != null){ accountIdsSet.add((id)sObj.get(fieldAPIName));// to query the account data adding the account id to accountIdsSet } if(ridAndAccIDMap.containsKey((Id)sObj.get(fieldAPIName))) {//to map related Id and account Id (One account may have multiple related Ids) ridAndAccIDMap.get((Id)sObj.get(fieldAPIName)).add((Id)sObj.get('id')); } else { Set<Id> ridSet = new Set<Id> {(Id)sObj.get('id')}; ridAndAccIDMap.put((Id)sObj.get(fieldAPIName),ridSet); } } } if(!accountIdsSet.isEmpty()) { Map<Id,Account> accountsMap = new Map<Id,Account>([select id, name, Service_Model_Indicator__c, Account_Status__c from Account where Id IN: accountIdsSet]); for(Id aid: ridAndAccIDMap.keySet()) { // to get account data in task or event handler based on the related Id we are adding them to map, for(Id rid : ridAndAccIDMap.get(aid)) { accountDataMap.put(rid, accountsMap.get(aid)); } } } return accountDataMap; } /* Method Name: FindAreaRole * Return Type: String * Parameters : String divisionNumber * Description: This method is used retur */ public static String findArea(String divisonNumber){ String areaRoleId = ''; UserRole userRole=[Select Id,ParentRoleId,Name from UserRole where Name = : divisonNumber]; areaRoleId = String.valueOf(userRole.ParentRoleId); return areaRoleId; } /* Method Name: getChildRoles * Return Type: Set<Id> * Parameters : String parentRoleId * Description: getChildRoles takes in the parentRoleId and returns set of childRoleIds. parentRoleId is not included in the set. */ public static Set<Id> getChildRoles (string parentRoleId) { Map <String,Set<Id>> roleMap = new Map <string,Set<Id>>(); // Build Map of Parent Role Id as the key with a set of it's immidiate child records as the value of the map for (UserRole roles : [Select ParentRoleId, Id From UserRole where ParentRoleId != null]) { if(roleMap.containsKey(roles.ParentRoleId) ) { roleMap.get(roles.ParentRoleId).add(roles.Id); } else { roleMap.put(roles.ParentRoleId, new Set<ID>{roles.Id}); } //system.debug('Parent: ' + roles.ParentRoleId); //system.debug('Set of child: ' + roleMap.get(roles.ParentRoleId)); } Set<Id> childRoles = getRoleSubordinateSet (roleMap,parentRoleId); //system.debug('Set of all childRoles: '+ childRoles); return childRoles; } /* Method Name: getRoleSubordinateSet * Return Type: Set<Id> * Parameters : Map of <ParentRoleId, Set of immidiate child records>, string of roleId * Description: Internal recursive method that will return a set of subordinate childRoleIds */ private static Set<Id> getRoleSubordinateSet (Map <String,Set<Id>> mapRoles, string roleId) { Set<Id> childRoles = new Set<id>(); //RK : the below line of code RoleId is added to check if the assigned to role and logged in user role division number childRoles.add(roleId); if(mapRoles.containsKey(roleId)) { for(Id id : mapRoles.get(roleId)) { childRoles.add(id); //recursive call childRoles.addAll(getRoleSubordinateSet(mapRoles,id)); } } return childRoles; } /* Method Name: getUserRoleNames * Return Type: Map<Id, String> * Parameters : Set<Id> UserId * Description: getUserRoleNames takes in a set of user Ids and returns a Map with <Id:User Id, String:User Role Name> */ public static Map<Id, String> getUserRoleNames(Set<Id> UserIds) { try{ Map<Id, String> UserRoleNames = new Map<Id, String>(); for(User usr: [SELECT UserRole.Name FROM User WHERE Id = :UserIds]){ UserRoleNames.put(usr.id, usr.UserRole.Name); } return UserRoleNames; } catch(Exception e) { return null; } } /** * Method Name : buildTime * arguments : String * returnType : Datetime */ public static Datetime buildTime(String rawTime){ Integer hrs; Integer mns; if(rawTime.endsWith(am_time)){ String tme = rawTime.split(empty_Space)[0]; List<String> tmestring = tme.split(split_Time); if(tmestring[0] == number_Twelve){ hrs = 0; mns = Integer.valueOf(tmestring[1]); } else { hrs = Integer.valueOf(tmestring[0]); mns = Integer.valueOf(tmestring[1]); } } else { String tme = rawTime.split(empty_Space)[0]; List<String> tmestring = tme.split(split_Time); if(tmestring[0] == number_Twelve){ hrs = Integer.valueOf(tmestring[0]); mns = Integer.valueOf(tmestring[1]); } else { hrs = Integer.valueOf(tmestring[0])+12; mns = Integer.valueOf(tmestring[1]); } } date dt = date.today(); Datetime finalDT = Datetime.newInstance(dt.year(), dt.month(), dt.day(), hrs, mns, 0); // system.debug('FFInal time'+finalDT); return finalDT; } /* Method Name: getRoleSubordinateUsers * Return Type: Map<Id, String> * Parameters : Set<Id> UserId * Description: getUserRoleNames takes in a Role Ids and returns a set of user Ids */ public static Set<ID> getRoleSubordinateUsers(Id roleId) { // get all of the roles underneath the user Set<Id> allSubRoleIds = getAllSubRoleIds(new Set<ID>{roleId}); // get all of the ids for the users in those roles Map<Id,User> users = new Map<Id, User>([Select Id, Name From User where UserRoleId IN :allSubRoleIds]); // return the ids as a set so you can do what you want with them return users.keySet(); } /* Method Name: getAllSubRoleIds * Return Type: Set<Id> currentRoleIds * Parameters : Set<Id> currentRoleIds * Description: getAllSubRoleIds takes in a set of role Ids and returns set of all Subordinate Role Ids */ private static Set<ID> getAllSubRoleIds(Set<ID> roleIds) { Set<ID> currentRoleIds = new Set<ID>(); // get all of the roles underneath the passed roles for(UserRole userRole :[select Id from UserRole where ParentRoleId IN :roleIds AND ParentRoleID != null]) currentRoleIds.add(userRole.Id); // go fetch some more rolls! if(currentRoleIds.size() > 0) currentRoleIds.addAll(getAllSubRoleIds(currentRoleIds)); return currentRoleIds; } }
- newbiewithapex
- February 18, 2019
- Like
- 0
How do I create test class for Task assignment method?
I have here the helper class to create task based on custom setting. How do I write test class for this methods in main class. Here is my main
public class PMO_Task_Assignment { public static void PMO_Task_Assignment(List<IDC_Task__c> lstTask){ // Map to get task order vs. custom setting value Map<String, PMO_TaskAssignment__c> alltasks = PMO_TaskAssignment__c.getAll(); // Map to get values to create defect Map<String, PMO_CreateDefect__c> alldefects = PMO_CreateDefect__c.getAll(); // Map to get task type vs completed IDC Task Map<String, IDC_Task__c> tasks = new Map<String, IDC_Task__c>(); // List of new Task Types List<string> lstnewtasktype = new List<string>(); // List of completed IDC Tasks List<IDC_Task__c> lstexistingTask = new List<IDC_Task__c>(); // List of new IDC Tasks List<IDC_Task__c> lstnewTask = new List<IDC_Task__c>(); // Creating a Map of Task type and completed IDC Task for(IDC_Task__c t: lstTask) { if(alltasks.containskey(t.Task_Type__c)){ tasks.put(PMO_TaskAssignment__c.getInstance(t.task_type__c).Task__c,t); } } // Looping through all values in custom setting and creating list of new task types as well as completed tasks in same order for(PMO_TaskAssignment__c task : alltasks.values()) { if(tasks.containskey(PMO_TaskAssignment__c.getInstance(task.name).Preceding_Task__c)){ lstnewtasktype.add(PMO_TaskAssignment__c.getInstance(task.name).Task__c); lstexistingTask.add(tasks.get(PMO_TaskAssignment__c.getInstance(task.name).Preceding_Task__c)); } } List<Defect__c> lstdefect = new List<Defect__c>(); // Creating new tasks and adding them in the list for(integer counter=0;counter<lstnewtasktype.size();counter++){ if(lstnewtasktype[counter] != system.label.PMO_Task_CodeReview || (lstnewtasktype[counter] == system.label.PMO_Task_CodeReview && lstexistingTask[counter].Build_Task_Type__c == system.label.PMO_TaskType_Customization)){ IDC_Task__c IDCTask = new IDC_Task__c(); //if(!TL.isEmpty()) if(PMO_TaskAssignment__c.getInstance(lstnewtasktype[counter]).Owner_Queue__c != null){ IDCTask.OwnerId = PMO_TaskAssignment__c.getInstance(lstnewtasktype[counter]).Owner_Queue__c; } IDCTask.Assigned_Date__c = system.today(); IDCTask.Task_Type__c = lstnewtasktype[counter]; IDCTask.IDC_Task__c = lstexistingTask[counter].id; IDCTask.Track__c = lstexistingTask[counter].Track__c; IDCTask.Request__c = lstexistingTask[counter].Request__c; if((lstexistingTask[counter].Defect_Found__c == true && (lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Review) || lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Execution))) || (!lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Review) && !lstexistingTask[counter].Task_Type__c.contains(system.label.PMO_Task_Execution))) lstnewtask.add(IDCTask); } try{ if( lstexistingTask[counter].Defect_Found__c == true && lstexistingTask[counter].Defect_Description__c != null && PMO_CreateDefect__c.getInstance(lstexistingTask[counter].Task_Type__c).Create_Defect__c == true){ Defect__c dfct = new Defect__c(); Dfct.subject__c = system.label.PMO_Defect_Subject + lstexistingTask[counter].Request_Name__c; Dfct.status__c = system.label.PMO_Defect_Open; Dfct.Defect_Detected__c = lstexistingTask[counter].Task_Type__c; Dfct.Detailed_Description__c = lstexistingTask[counter].Defect_Description__c; if(lstexistingTask[counter].Request__c != null) Dfct.Related_Request__c = lstexistingTask[counter].Request__c; lstdefect.add(Dfct); } } catch(exception ex){ ex.setMessage(system.label.PMO_Task_Error); } } // insert the list if(!lstnewtask.isEmpty()) { try { insert lstnewtask; insert lstdefect; } catch(DMLException ex){ ex.setMessage(system.label.PMO_Task_Error); } } } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How do I write test class for sort methods?
I have a class which has different sort methods and I need help writing test class for those methods. Here is my main class.
public class TrialCustomerPortalHomePageController { User loggedInUser = [Select id,contactId,Contact.AccountId from User where id = :UserInfo.getUserId()]; public List<Asset> MyRegisteredProducts {get; set;} public List<Case> MyRecentCases {get; set;} public List<Solution> TopSolutions {get; set;} public List<Idea> PopularIdeas {get; set;} public String sortField1 {get; set;} public String previousSortField1 {get; set;} public String sortField2 {get; set;} public String previousSortField2 {get; set;} public String sortField3 {get; set;} public String previousSortField3 {get; set;} public String sortField4 {get; set;} public String previousSortField4 {get; set;} public TrialCustomerPortalHomePageController() { MyRegisteredProducts = [select id,Name,SerialNumber,InstallDate,UsageEndDate,Status from Asset where ContactId = :loggedInUser.ContactId order by SerialNumber desc limit 3]; MyRecentCases = [select id,CaseNumber,Subject,Status,LastModifiedDate from Case where ContactId = :loggedInUser.ContactId order by LastModifiedDate desc limit 3]; TopSolutions = [select id,SolutionName,TimesUsed,LastModifiedDate from Solution order by TimesUsed desc limit 3]; PopularIdeas = [select id,Title,Categories,VoteTotal from Idea order by VoteTotal desc limit 3]; } public void SortProducts(){ String order = 'asc'; if(previousSortField1 == sortField1){ order = 'desc'; previousSortField1 = null; }else{ previousSortField1 = sortField1; } superSort.sortList(MyRegisteredProducts,sortField1,order); } public void SortCases(){ String order = 'asc'; if(previousSortField2 == sortField2){ order = 'desc'; previousSortField2 = null; }else{ previousSortField2 = sortField2; } superSort.sortList(MyRecentCases,sortField2,order); } public void SortSolutions(){ String order = 'asc'; if(previousSortField3 == sortField3){ order = 'desc'; previousSortField3 = null; }else{ previousSortField3 = sortField3; } superSort.sortList(TopSolutions,sortField3,order); } public void SortIdeas(){ String order = 'asc'; if(previousSortField4 == sortField4){ order = 'desc'; previousSortField4 = null; }else{ previousSortField4 = sortField4; } superSort.sortList(PopularIdeas,sortField4,order); } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How do I write test class for contact search method?
I have a main class that search contact records and I am looking for any help on how to write test class for this method. Here is my main class look like. I am not fimiliar with @RestResource and @HttpGet.
@RestResource(urlMapping='/contactsSearch/*') global without sharing class REST_GetContactsSearch { @HttpGet global static ContactList doGet() { RestRequest req = RestContext.request; RestResponse res = RestContext.response; String term = RestContext.request.params.get('term'); String contactQueryStr = 'SELECT Name,Id,Title,Email,Phone,MobilePhone,Account.Name,PhotoUrl FROM Contact WHERE Email != null AND OwnerId = \'' + UserInfo.getUserId() + '\' AND IsDeleted = false'; if(!String.isEmpty(term) && term.length() >= 2){ term = '%' + term + '%'; contactQueryStr += ' AND Name LIKE \'' + term + '\''; } System.debug('@@@@ contactQueryStr: ' + contactQueryStr); List<Contact> contacts = Database.query(contactQueryStr); ContactList contactsList = new ContactList(); contactsList.contacts = contacts; return contactsList; } global class ContactList { public List<Contact> contacts; public ContactList () { contacts = null; } } }
- newbiewithapex
- February 14, 2019
- Like
- 0
How to write test class to validate customer order?
I have this class as a controller for the customer order validate component . I need help writing test class for this one. Any kind of help would be much appreciate.
public class CustomerOrderValidateCntrl { @AuraEnabled public static UserNAccountDetails getParamDetails(String accId) { Account acc = getAccountDetails(accId); boolean profilecheckfailed = false; profilecheckfailed = isProfileNotToBeAllowed(); system.debug('Tandem: '+acc.Tandem_Account_Number__c); return new UserNAccountDetails(profilecheckfailed,acc.Tandem_Account_Number__c,acc.Division_Number__c,getUserDetails()); } public static Account getAccountDetails(String accId) { return [SELECT Id, Tandem_Account_Number__c, Division_Number__c FROM Account WHERE Id = :accId LIMIT 1]; } public static String getUserDetails() { User usr = [SELECT Id, Network_Id__c FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1]; return usr.Network_Id__c; } public static boolean isProfileNotToBeAllowed(){ SalesforceIds__c profileIds = SalesforceIds__c.getOrgDefaults(); return (UserInfo.getProfileId().contains(profileIds.Profile_USF_ChefStoreRep__c)); } public class UserNAccountDetails{ @AuraEnabled public Boolean profileCheckFailed {set;get;} @AuraEnabled public String tandemNumber {set;get;} @AuraEnabled public String divisionNumber {set;get;} @AuraEnabled public String networkId {set;get;} public UserNAccountDetails(Boolean profileCheckFailed, String tandemNumber, String divisionNumber, String networkId){ this.profileCheckFailed=profileCheckFailed; this.tandemNumber=tandemNumber; this.divisionNumber=divisionNumber; this.networkId=networkId; } } }
- newbiewithapex
- February 13, 2019
- Like
- 0