-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
18Questions
-
20Replies
How to put sObjects in combox in Lightning Web Component?
I want to show sObjects in a custom picklist like in Combobox in LWC- I know how to do with single object but am not able to understand how to fetch sObjects. Afer selecting that sOject - I need to display the details for that object.
- Raffus
- December 01, 2022
- Like
- 0
Not getting full coverage for this method
The complete code
webservice static string changeMultipleCases_Owner(list<string> listCaseIds){ string result = 'Success'; list<Case> lstAcceptCases = new list<Case>(); set<Id> setGroupIds = new set<Id>(); for(Case objCs:[Select Id,Owner_Name__c,OwnerId,Status,Case_Queue_Name__c from Case where Id IN:listCaseIds AND (Program_Type__c=null OR Program_Type__c='Customer Pulse')]){ if(string.valueof(objCs.OwnerId).startswith('00G')){ lstAcceptCases.add(objCs); setGroupIds.add(objCs.OwnerId); } } map<string,boolean> mapGroupMember = new map<string,boolean>(); if(setGroupIds!=null && setGroupIds.size()>0){ for(GroupMember GrpMem:[select Id,GroupId,UserOrGroupId from GroupMember where GroupId IN:setGroupIds]){ if(GrpMem.UserOrGroupId==userinfo.getuserid()){ mapGroupMember.put(GrpMem.GroupId,true); } } } list<Case> lstCases = new list<Case>(); for(Case cs:lstAcceptCases){ if((cs.Case_Queue_Name__c!=null && mapGroupMember.get(cs.OwnerId)!=null) || system.test.isRunningTest()){ Case objCS = new Case(Id=cs.Id); objCS.OwnerId = userInfo.getUserId(); lstCases.add(objCS); } } try{ CaseUtilityCls.Skip_Staus_Validation = true; if(lstCases!=null && lstCases.size()>0) update lstCases; }catch(Exception e){ result = e.getMessage()+''; } return result; }Test Method
@isTest public static void changeMultipleCases_OwnerTest(){ //test.startTest(); Survey_Detail__c sd = new Survey_Detail__c(); list<String> fieldList = new list<string>(); map<String,Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get('Survey_Detail__c').getDescribe().fields.getMap(); if(fieldMap != null){ for(Schema.SObjectField f : fieldMap.values()){ Schema.DescribeFieldResult fd = f.getDescribe(); if(fd.isAccessible() && fd.isCustom() && fd.isCreateable()){ string strDataType = fd.getType()+''; if(strDataType=='INTEGER' || strDataType=='DOUBLE') sd.put(fd.getName(),3); else if(strDataType=='DATE') sd.put(fd.getName(),system.today()); else if(strDataType=='DATETIME') sd.put(fd.getName(),system.now()); else if(strDataType=='BOOLEAN') sd.put(fd.getName(),true); else if(strDataType=='STRING' || strDataType=='PICKLIST') sd.put(fd.getName(),'123214'); } } sd.put('Email__c','leeba@nsiglobal.com'); sd.put('Cinema_name__c','The Beach'); sd.put('Brand__c',null); sd.put('CommentsBackup__c','Test Comments'); sd.put('Location_Code__c',null); sd.put('Share_your_contact_details__c', 'No'); //sd.put('Location_Code__c','Test Location'); sd.Response_Id__c = '12345'; insert sd; } Id rtid_acnt = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId(); Account acc = new Account(); acc.firstname = 'test'; acc.lastname = 'test'; acc.recordtypeid = rtid_acnt; acc.VIP__c = true; acc.PersonMobilePhone = '+965'; acc.U_by_Emaar_Tier__c = 'GLD'; insert acc; Contact con = new Contact(); con.firstname = 'test'; con.lastname = 'test'; con.mobilephone = '+965'; con.email = 'test@test.com'; //con.AccountId = acc.Id; insert con; // Opportunity Create. Opportunity objOpp = new Opportunity(); objOpp.Name = 'Test Opp Name'; objOpp.StageName = 'Qualification'; objOpp.amount = 5000; objOpp.CloseDate = System.today(); objOpp.Opportunity_ID__c = 'Test'; Insert objOpp; User usr = [Select id from User where Id = :UserInfo.getUserId()]; System.RunAs(usr){ Test.startTest(); Group qu = new Group(Name = 'Burj Khalifa', Type = 'Queue'); insert qu; GroupMember gm = new GroupMember(GroupId = qu.Id, UserOrGroupId = UserInfo.getUserId()); insert gm ; Survey__c sur = new Survey__c(); sur.Account__c = acc.Id; sur.Location__c = 'Burj Club'; sur.Outbound_Call_Survey__c = false; sur.Survey_Country__c = 'UAE'; sur.Division__c = 'Emaar Properties'; sur.Name = 'test1'; sur.Person_Email__c = 'a@atest.com'; sur.Survey_Response_ID__c = sd.Response_Id__c; sur.Opportunity_ID__c = objOpp.Id; insert sur; Case objcs3 = new Case(); objcs3.AccountId = sur.Account__c; objcs3.Priority = 'High'; objcs3.Survey__c = sur.Id; objcs3.Senior_Management_First_Name_c__c = 'test'; objcs3.Senior_Management_Last_Name_c__c = 'test'; objcs3.Customer_s_Comments__c = 'test'; objcs3.Customer_s_Suggestions__c = 'test'; objcs3.Senior_Management_Comments__c = 'test'; objcs3.Status = 'In Progress'; objcs3.Case_Queue_Name__c = qu.Name; objcs3.contactId = con.Id; objcs3.Case_Queue_Name__c = qu.Id; CaseUtilityCls.Skip_Staus_Validation = true; objcs3.Category__c = 'Technical Services'; objcs3.Level__c = '1'; Insert objcs3; update objcs3; List<Case_Status_Map__c> lstCSM = new List<Case_Status_Map__c>(); for(Integer i=1;i<=3;i++){ Case_Status_Map__c objCSM = new Case_Status_Map__c(); objCSM.Name = 'test2'+i; objCSM.Level__c = 'L'+i; if(i==1) objCSM.Queue_Name__c = 'Burj Khalifa Team Lead'; if(i==2) objCSM.Queue_Name__c = 'Burj Khalifa'; if(i==3) objCSM.Queue_Name__c = 'Burj Club GM'; lstCSM.add(objCSM); } if(lstCSM.size()>0) Insert lstCSM; set<Id> caseIds6 = new set<Id>(); List<Id> caseIds7 = new List<Id>(); caseIds6.add(objcs3.id); caseIds7.add(objcs3.Id); set<string> caseIds8 = new set<string>(); caseIds8.add(objcs3.id); CaseUtilityCls.changeMultipleCases_Owner(caseIds7); List<Auto_Escalation__c> lstAE = [SELECT Id from Auto_Escalation__c limit 10]; CaseUtilityCls.Auto_Escalate(objcs3,lstAE,'Burj Club GM'); System.debug('userinfo id ' + UserInfo.getUserId()); objcs3.Customer_Comments__c = 'Test comments'; update objcs3; //test.stopTest(); List<Escalate_Level__c > lstEL = [SELECT ID,Level__c from Escalate_Level__c limit 10]; CaseUtilityCls.EscalateCase(objcs3.Id); List<SLA_Time__c> lstSLA = new List<SLA_Time__c>(); for(Integer i=1;i<=3;i++){ SLA_Time__c objSLA = new SLA_Time__c(); objSLA.Name = 'test'+i; objSLA.Priority__c ='High'; if(i==1) objSLA.Queue_Name__c = 'Burj Khalifa Team Lead'; if(i==2) objSLA.Queue_Name__c = 'Burj Khalifa'; if(i==3) objSLA.Queue_Name__c = 'Burj Club GM'; lstSLA.add(objSLA); } if(lstSLA.size()>0) Insert lstSLA; caseIds8 = new set<String>(); caseIds8.add(objcs3.Id); test.stopTest(); } // test.startTest(); //test.stopTest(); }
- Raffus
- October 26, 2022
- Like
- 0
Not getting the full coverage for this test method
This line is not fetching any data
Code not covered
list<Escalate_Level__c> escalationQueueList = Escalate_Level__c.getAll().values();Because of that, this code is not covering
Code not covered
for(Escalate_Level__c escalateQueue:escalationQueueList){ boolean matchFound = false; system.debug('escalateQueue.Escalate_Category__c'+escalateQueue.Escalate_Category__c); if(escalateQueue.Level__c==cs.Level__c && escalateQueue.Queue_Name__c==cs.Case_Queue_Name__c ){ if(escalateQueue.Project_Name__c!=null && escalateQueue.Escalate_Category__c == null){ matchFound = (escalateQueue.Project_Name__c == cs.Project_Name__c); } system.debug('^^^match found1 '+matchFound); if(!matchFound && escalateQueue.Escalate_Category__c != null && escalateQueue.Project_Name__c!=null){ matchFound =(escalateQueue.Escalate_Category__c == cs.Escalation_Category__c && escalateQueue.Project_Name__c == cs.Project_Name__c); } system.debug('^^^match found2 '+matchFound); if(!matchFound && escalateQueue.Escalate_Category__c != null && escalateQueue.Project_Name__c==null){ matchFound =(escalateQueue.Escalate_Category__c == cs.Escalation_Category__c && escalateQueue.Queue_Name__c == cs.Case_Queue_Name__c); } system.debug('^^^match found3 '+matchFound); if(!matchFound && escalateQueue.Location__c==null && escalateQueue.Category__c==null && escalateQueue.Escalate_Category__c == null){ matchFound = (escalateQueue.Brand__c == cs.Brand__c && escalateQueue.Division__c == cs.Division__c && escalateQueue.Queue_Name__c == cs.Case_Queue_Name__c); } system.debug('^^^match found4 '+matchFound); if(!matchFound && escalateQueue.Location__c!=null && escalateQueue.Category__c==null && escalateQueue.Escalate_Category__c == null){ matchFound = (escalateQueue.Brand__c == cs.Brand__c && escalateQueue.Division__c == cs.Division__c && escalateQueue.Queue_Name__c == cs.Case_Queue_Name__c && escalateQueue.Location__c == cs.Location_CS__c); }A test method that I have written
static testmethod void myUnitEscalateCaseTest(){ test.startTest(); Survey_Detail__c sd = new Survey_Detail__c(); list<String> fieldList = new list<string>(); map<String,Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get('Survey_Detail__c').getDescribe().fields.getMap(); if(fieldMap != null){ for(Schema.SObjectField f : fieldMap.values()){ Schema.DescribeFieldResult fd = f.getDescribe(); if(fd.isAccessible() && fd.isCustom() && fd.isCreateable()){ string strDataType = fd.getType()+''; if(strDataType=='INTEGER' || strDataType=='DOUBLE') sd.put(fd.getName(),3); else if(strDataType=='DATE') sd.put(fd.getName(),system.today()); else if(strDataType=='DATETIME') sd.put(fd.getName(),system.now()); else if(strDataType=='BOOLEAN') sd.put(fd.getName(),true); else if(strDataType=='STRING' || strDataType=='PICKLIST') sd.put(fd.getName(),'123214'); } } sd.put('Email__c','leeba@nsiglobal.com'); sd.put('Cinema_name__c','The Beach'); sd.put('Brand__c',null); sd.put('CommentsBackup__c','Test Comments'); sd.put('Location_Code__c',null); sd.put('Share_your_contact_details__c', 'No'); //sd.put('Location_Code__c','Test Location'); sd.Response_Id__c = '12345'; insert sd; } Id rtid_acnt = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId(); Account acc = new Account(); acc.firstname = 'test'; acc.lastname = 'test'; acc.recordtypeid = rtid_acnt; acc.VIP__c = true; acc.PersonMobilePhone = '+965'; acc.U_by_Emaar_Tier__c = 'GLD'; insert acc; Contact con = new Contact(); con.firstname = 'test'; con.lastname = 'test'; con.mobilephone = '+965'; con.email = 'test@test.com'; //con.AccountId = acc.Id; insert con; // Opportunity Create. Opportunity objOpp = new Opportunity(); objOpp.Name = 'Test Opp Name'; objOpp.StageName = 'Qualification'; objOpp.amount = 5000; objOpp.CloseDate = System.today(); objOpp.Opportunity_ID__c = 'Test'; Insert objOpp; Survey__c sur = new Survey__c(); sur.Account__c = acc.Id; sur.Location__c = 'Burj Club'; sur.Outbound_Call_Survey__c = false; sur.Survey_Country__c = 'UAE'; sur.Division__c = 'Emaar Properties'; sur.Name = 'test1'; sur.Person_Email__c = 'a@atest.com'; sur.Survey_Response_ID__c = sd.Response_Id__c; sur.Opportunity_ID__c = objOpp.Id; insert sur; Case objcs3 = new Case(); objcs3.AccountId = sur.Account__c; objcs3.Priority = 'High'; objcs3.Survey__c = sur.Id; objcs3.Senior_Management_First_Name_c__c = 'test'; objcs3.Senior_Management_Last_Name_c__c = 'test'; objcs3.Customer_s_Comments__c = 'test'; objcs3.Customer_s_Suggestions__c = 'test'; objcs3.Senior_Management_Comments__c = 'test'; objcs3.Status = 'In Progress'; objcs3.contactId = con.Id; objcs3.Level__c = 'Test'; objcs3.Case_Queue_Name__c = 'Test'; objcs3.Case_Queue_Name__c = ' GM'; CaseUtilityCls.Skip_Staus_Validation = true; objcs3.Category__c = 'Technical Services'; Insert objcs3; update objcs3; List<Case_Status_Map__c> lstCSM = new List<Case_Status_Map__c>(); for(Integer i=1;i<=3;i++){ Case_Status_Map__c objCSM = new Case_Status_Map__c(); objCSM.Name = 'test2'+i; objCSM.Level__c = 'L'+i; if(i==1) objCSM.Queue_Name__c = Team Lead'; if(i==2) objCSM.Queue_Name__c = 'Khalifa'; if(i==3) objCSM.Queue_Name__c = 'GM'; lstCSM.add(objCSM); } if(lstCSM.size()>0) Insert lstCSM; List<Escalate_Level__c> objElList = new List<Escalate_Level__c>(); for(Integer i=1;i<=3;i++){ Escalate_Level__c objSLA = new Escalate_Level__c(); objSLA.Name = 'test'+i; if(i==1) objSLA.Brand__c ='High'; objSLA.Category__c = 'Test'; objSLA.Division__c = 'Test'; objSLA.Escalate_Category__c = NULL; objSLA.Level__c = 'Test'; objSLA.Location__c = 'Test'; objSLA.Next_Escalation_Queue__c = 'Test'; objSLA.Next_Level__c = 'Test'; objSLA.Project_Name__c = 'Test'; objSLA.Queue_Name__c = 'Team Lead'; if(i==2) objSLA.Brand__c ='High'; objSLA.Category__c = 'Test'; objSLA.Division__c = 'Test'; objSLA.Escalate_Category__c = NULL; objSLA.Level__c = 'Test'; objSLA.Location__c = 'Test'; objSLA.Next_Escalation_Queue__c = 'Test'; objSLA.Next_Level__c = 'Test'; objSLA.Project_Name__c = 'Test'; objSLA.Queue_Name__c = 'Khalifa'; if(i==3) objSLA.Brand__c ='High'; objSLA.Division__c = 'Test'; objSLA.Escalate_Category__c = NULL; objSLA.Level__c = 'Test'; objSLA.Location__c = 'Test'; objSLA.Next_Escalation_Queue__c = 'Test'; objSLA.Next_Level__c = 'Test'; objSLA.Project_Name__c = 'Test'; objSLA.Queue_Name__c = 'Club GM'; objElList.add(objSLA); } insert objElList; Set<Id> caseIds6 = new set<Id>(); caseIds6.add(objcs3.id); CaseUtilityCls.UpdateCaseStatus(caseIds6); CaseUtilityCls.EscalateCase(objcs3.Id); CaseUtilityCls.changeCaseOwner(objcs3.Id); test.stopTest(); }
- Raffus
- October 26, 2022
- Like
- 0
Not able to cover this line of code, enrollmentsId are not inserted
This is method
This mine test method
public static void carriersBMLLUpdatecreateCaseComments(List<Enrollment__c> newList,Map<Id,Enrollment__c> oldMap) { Set<Id> enrollmentIds = new Set<Id>(); Map<Id, Enrollment__c> newMap = new Map<Id, Enrollment__c>(newList); for(Enrollment__c enrollment: newList) { //on update if(oldMap!=null) { if(enrollment.Enrollment_Method__c == Label.AFocus_ThirdParty_PickVal){ if(enrollment.Carriers_BMLL_will_not_be_the_GA__c !=null && enrollment.Carriers_BMLL_will_not_be_the_GA__c != oldMap.get(enrollment.Id).Carriers_BMLL_will_not_be_the_GA__c) { enrollmentIds.add(enrollment.Id); } } } //on insert else if(oldMap==null){ if(enrollment.Enrollment_Method__c == Label.AFocus_ThirdParty_PickVal){ if(enrollment.Carriers_BMLL_will_not_be_the_GA__c == null || enrollment.Carriers_BMLL_will_not_be_the_GA__c =='') { enrollmentIds.add(enrollment.Id); } } } } System.debug('enrollmentIds are'+enrollmentIds); List<Case> enrollmentCases = new List<Case>(); List<CaseComment> CaseCommentsList = new List<CaseComment>(); if(enrollmentIds.size()>0) { enrollmentCases = [Select Id,Enrollment__c,Enrollment__r.Carriers_BMLL_will_not_be_the_GA__c,Enrollment__r.Enrollment_Method__c from Case where Enrollment__c IN :enrollmentIds AND Recordtype.Name = :Label.AFocus_New_Business_Case]; if(enrollmentCases.size()>0) { for(Case enrollemtCase:enrollmentCases) { CaseComment caseComment = new CaseComment(); caseComment.ParentId = enrollemtCase.Id; caseComment.IsPublished = false; caseComment.CommentBody = 'ATTN:New Business Team Carriers BMLL will not be the GA:['+ enrollemtCase.Enrollment__r.Carriers_BMLL_will_not_be_the_GA__c +'] When Services are created for this Carriers add $0 in SCA PEPM field on each Service'; CaseCommentsList.add(caseComment); } } } System.debug('CaseCommentsList is :' + CaseCommentsList); try{ if(!CaseCommentsList.isEmpty()){ insert CaseCommentsList; } } catch(Exception ex){ // ExceptionHandlerController.logErrorsInboundAPI('Sync BenAdminBuildCase Notes with Enrollment Notes','AFocus_EnrollmentTriggerHandler','updatecaseNotesFromEnrollmentNotes',ex.getMessage(),'Case ids to be updated' +caseUpdatedList,'Exception occurred during updating status',UserInfo.getUserId(),'Error'); ExceptionHandlerController.logErrorsInboundAPI('Create Case Comments when Carriers_BMLL_will_not_be_the_GA__c is updated','AFocus_EnrollmentTriggerHandler','carriersBMLLUpdatecreateCaseComments',ex.getMessage(),'Carriers_BMLL_will_not_be_the_GA__c to be updated' +CaseCommentsList,'Exception occurred during updating Carriers_BMLL_will_not_be_the_GA__c',UserInfo.getUserId(),'Error'); } }
This mine test method
@isTest static void carriersBMLLUpdatecreateCaseCommentsTest(){ Set<Id> enrollmentIds = new Set<Id>(); string Id =[SELECT id from RecordType where Name ='Agency'].Id; Account Acc1 = new Account(); Acc1.Name = 'Test Account forth'; Acc1.Email__c='testtest@gmail.com'; Acc1.Source_System__c ='BenefitPoint'; Acc1.Technology_Adoption__c ='Low - Not Open'; Acc1.RecordTypeId = Id; insert Acc1; System.debug('Account info: ' + Acc1); List<Enrollment__c> enlist = new List<Enrollment__c>(); Enrollment__c en1 = new Enrollment__c(); en1.Broker__c= Acc1.id; en1.Status__c='Not Submitted'; en1.Notes__c='Test Notes'; en1.Plan_Selection_Complete__c= true; en1.Street__c = 'eStreet'; en1.city__c = 'New york'; en1.State__c = 'NY'; en1.Zip__c = '48979842'; en1.Effective_Date__c = system.today(); en1.Client_Type_Status__c = 'Group'; en1.EIN__c = '281764'; en1.Phone__c = '(555) 123-4567'; en1.Full_Time_Employees__c = 80; en1.Enrollment_Method__c='Third-party'; en1.Carriers_BMLL_will_not_be_the_GA__c ='test'; insert en1; enlist.add(en1); //insert enlist; System.debug('Enrollment1 info: ' + en1); enrollmentIds.add(en1.Id); Map<Id,Enrollment__c> eListMap = new Map<Id,Enrollment__c>(); eListMap.put(en1.Id,en1); system.debug('elistMap '+ eListMap); Id RTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Benefit New Business / Renewal').getRecordTypeId(); case caseRec=new case(); caseRec.RecordTypeId = RTypeId; caseRec.Origin='Sales Escalation'; caseRec.SuppliedEmail='test1234@test1234.com'; caseRec.Reason='APS'; caseRec.subject='Installation Problem'; //caseRec.AccountId=accGpRec.id; caseRec.Status = 'New'; caseRec.Approval_Status__c = 'Not Submitted'; //caseRec.NBA_Rep__c = UserInfo.getUserId(); caseRec.Enrollment__c = en1.Id; insert caseRec; System.debug('Case1 info: ' + caseRec); CaseComment comment1 = new CaseComment(); comment1.ParentId = caseRec.Id; comment1.CommentBody = 'Case record 1 comment'; comment1.IsPublished = TRUE; insert comment1; System.debug('Case comment ' + comment1); AFocus_EnrollmentTriggerHandler.carriersBMLLUpdatecreateCaseComments(enlist,eListMap); }
- Raffus
- October 01, 2022
- Like
- 0
How to write a test class for following method
public void onLoad() { Map<String, String> mapParams = Apexpages.currentPage().getParameters(); if (!mapParams.isEmpty()){ if (mapParams.containsKey('emailid')) { system.debug('inside decrypt---'); String emailidApp = FSLCryptoHelper.getInstance().decryptOmni(mapParams.get('emailid')); emailid = emailidApp.toLowercase(); system.debug('inside decrypt---'+emailid); } if (mapParams.containsKey('empid')) { system.debug('inside decrypt empid---'); empid = FSLCryptoHelper.getInstance().decryptOmni(mapParams.get('empid')); system.debug('inside decrypt emailid---'+emailid); } if (mapParams.containsKey('jwt-token')) { system.debug('inside decrypt jwttoken---'); jwttoken = FSLCryptoHelper.getInstance().decryptOmni(mapParams.get('jwt-token')); system.debug('inside decrypt jwttoken---'+jwttoken); } }
My test class
@isTest static void onLoadTest(){ PageReference testPage = Page.OmniAppPage; Test.setCurrentPage(testPage); testPage.getParameters().put('emailid', 'test@test.com'); testPage.getParameters().put('empid', '1233'); testPage.getParameters().put('jwt-token', '1233'); OmniAppController oac = new OmniAppController(); oac.onLoad(); }FSLCryptoHelper.decryptOmni method
public String decryptOmni(String dataToDecrypt) { System.debug('VV Before dataToDecrypt -->'+dataToDecrypt); String decryptedData = ''; if (dataToDecrypt != null) { dataToDecrypt = dataToDecrypt.replaceAll(' ', '+'); Blob data = EncodingUtil.convertFromHex(dataToDecrypt); System.debug('VV before dataToDecrypt -->'+dataToDecrypt); Blob decryptedBlob = Crypto.decrypt(ALGORITHM_AES256, ONEAPP_KEY, ONEAPP_IV, data); System.debug('VV After decryptedBlob -->'+decryptedBlob); decryptedData = decryptedBlob.toString(); System.debug('VV After decryptedData -->'+decryptedData); } return decryptedData; }Getting this error -
"System.InvalidParameterValueException: input string must be an even number of characters long, but was 13"
On line - Blob data = EncodingUtil.convertFromHex(dataToDecrypt);
- Raffus
- September 15, 2022
- Like
- 0
How do I parse a JSON map into an Apex Map in Object
I want to coverage for this method-
My written test class but not able to put data for map
@future (callout=true) public static void fetchDetailsAndUpdateOmniCustomer(String emailid, String empid, String jwttoken) { // Omni_App_Customer__c customer = [SELECT Id,Name, Customer_Last_Name__c, Customer_Email__c, Customer_Photo_Base64__c, Customer_Emp_ID__c, Customer_First_Name__c, Customer_Name__c, Party_Id__c FROM Omni_App_Customer__c WHERE Customer_Email__c= : emailid]; System.debug('customers getOrCreateCustomer' + customer); String employeeDetails = getDataFromEmployee(empid, emailid, jwttoken);//String Map<String, Object> employeeAllData = (Map<String, Object>)JSON.deserializeUntyped(employeeDetails); Map<String, Object> empCardDetails = (Map<String, Object>)employeeAllData.get('EmpCardDetailsOutputParameters'); System.debug('customers empCardDetails' + empCardDetails); If(empCardDetails != null){ Map<String, Object> p_refcur = (Map<String, Object>)empCardDetails.get('P_REFCUR'); System.debug('customers p_refcur' + p_refcur); If(p_refcur != null){ Map<String, Object> row = (Map<String, Object>)p_refcur.get('Row'); System.debug('customers row' + row); List<Object> employee = (List<Object>)row.get('Column'); for(object obj : employee){ String employeeData = JSON.serialize(obj); if(employeeData.contains('FIRST_NAME')){ customer.Customer_First_Name__c = getFieldValue(employeeData); customer.Name = customer.Customer_First_Name__c; }else if(employeeData.contains('LAST_NAME')){ customer.Customer_Last_Name__c = getFieldValue(employeeData); customer.Name = customer.Name +' '+customer.Customer_Last_Name__c; }else if(employeeData.contains('EMPLOYEE_PHOTO')){ String empPhoto = getFieldValue(employeeData); if(String.isNotBlank(empPhoto)){ String empPhotoFinal = empPhoto.replaceAll('\n', ''); customer.Customer_Photo_Base64__c = 'data:image/jpeg;base64,'+empPhotoFinal; } }else if(employeeData.contains('DEPARTMENT')){ customer.Customer_Department__c = getFieldValue(employeeData); } } } } customer.recalculateFormulas(); System.debug('before upsert FromFuture customer ' + customer); upsert customer; }
My written test class but not able to put data for map
@IsTest public static void fetchDetailsAndUpdaterandCustomerTest(){ // String employeeDetails = '{"emailid":["emailid":"test@g.com"]}'; // randAppController.saveCustomerInfo(jsoninput,'12133','09922982822'); rand_App_Customer__c randCustomer = new rand_App_Customer__c(); randCustomer.Customer_ID__c = '1234567'; randCustomer.Customer_First_Name__c = 'Test rand'; randCustomer.Customer_Last_Name__c = 'Customer'; randCustomer.Party_Id__c = '8545254752'; randCustomer.Customer_Mobile__c = '8545254752'; randCustomer.Customer_Email__c = 'tannow@tan.ae'; randCustomer.Customer_Emp_ID__c = '012081'; randCustomer.Customer_Points__c = 150; randCustomer.Customer_Department__c = 'EMG - Leasing'; Insert randCustomer; String jwttoken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0LXN1YmplY3QiLCJhdWQiOlsiYXVkaWVuY2UxIiwiYXVkaWVuY2UyIl0sImlzcyI6InVybjpcL1wvYXBpZ2VlLWVkZ2UtSldULXBvbGljeS10ZXN0IiwiYWZmaWxpYXRlIjoiZmFsc2UiLCJleHAiOjE2NjIxODUwMTUsInVzZXJpZCI6IkVtYWFybm93IiwiaWF0IjoxNjYyMTEzMDE1LCJqdGkiOiJjYWNkN2MxZC02NDY5LTQyMjUtYmU5ZC0yZDExNmFkMjk0MGUiLCJ1c2VybmFtZSI6IkVtYWFybm93QGVtYWFyLmFlIn0.BJRby7mdcJ_IAoEJJwruGJod6dd8IS3nuWOQIK0dFhU'; String employeeId = '012081'; String employeeEmail = 'tannow@tan.ae'; String employeeDetails = '{"EmpCardDetailsOutputParameters": { "P_REFCUR": { "Row": { "Column": [{ "@name": "EMPLOYEE_NAME","@sqltype": "VARCHAR2","TEXT": "Shinu Sony"},{"@name": "EMPLOYEE_NUMBER","@sqltype": "VARCHAR2","TEXT": "011380"},{"@name": "DESIGNATION", "@sqltype": "VARCHAR2","TEXT": "Product Owner"},{"@name": "DEPARTMENT","@sqltype": "VARCHAR2","TEXT": "Information Technology"},{"@name": "ENTITY","@sqltype": "VARCHAR2","TEXT": "tan Properties P.J.S.C."},{"@name": "EMAIL_ADDRESS","@sqltype": "VARCHAR2","TEXT": "SSony@tan.ae"},{"@name": "PHONE","@sqltype": "VARCHAR2","TEXT": "+971567646583"},{"@name": "COMPANY_CODE","@sqltype": "VARCHAR2","TEXT": "Non EHG"},{"@name": "FIRST_NAME","@sqltype": "VARCHAR2","TEXT": "Shinu"},{"@name": "LAST_NAME","@sqltype": "VARCHAR2","TEXT": "Sony"},{"@nil": "true","@name": "MIDDLE_NAMES","@sqltype": "VARCHAR2"},{"@name": "LOGO_NAME", "@sqltype": "VARCHAR2","TEXT": "tan Properties P.J.S.C."},{"@name": "EMPLOYEE_PHOTO", "@sqltype": "CLOB","TEXT": "test" } ]}}}}'; Map<String, Object> employeeAllData = (Map<String, Object>) JSON.deserializeUntyped(employeeDetails); Map<String, Object> empCardDetails = (Map<String, Object>)employeeAllData.get('EmpCardDetailsOutputParameters'); Map<String, Object> p_refcur = (Map<String, Object>)empCardDetails.get('P_REFCUR'); Map<String, Object> row = (Map<String, Object>)p_refcur.get('Row'); List<Object> employee = (List<Object>)row.get('Column'); Test.startTest(); try { randAppController.fetchDetailsAndUpdaterandCustomer(employeeEmail, employeeId, jwttoken); } catch(exception e) { } Test.stopTest(); }
- Raffus
- September 13, 2022
- Like
- 0
Written a test class but few Lines are not covered?
I have written a test class but a few lines are not covered. I do not understand how to cover it. Please help!!!
These lines are not covered by the above code.
@AuraEnabled public static demoWrapper getData(String Club){ String userId= User.getLoggedInUserId(); List<User> userRec = [Select Id, Name,accountId,ContactId,ViewActivity__c from User where Id =: userId]; List<BTS__c> BTSList = new List<BTS__c>(); List<Services__c> serviceList = new List<Services__c>(); Integer percentage = 0; demoWrapper wrapperobj = new demoWrapper(); String accountIdstr = userRec[0].accountId; if(accountIdstr <> null && accountIdstr != ''){ serviceList = [Select id, Account__c,Account__r.RecordType.Name,Account__r.CreatedDate,Broker_of_Record__c, Broker_of_Record__r.Club__c from Services__c where Broker_of_Record__c =: accountIdstr AND Account__r.RecordType.Name = 'Group']; BTSList = [Select id, name, RPoints__c,Milestone_Date__c,RecordType.Name,Trip_Status_Eligibility__r.Pinnacle_Target_Points__c,Trip_Status_Eligibility__r.RecordType.Name, Trip_Status_Eligibility__r.Premier_Target_Points__c,Trip_Status_Eligibility__r.Preferred_Target_Points__c, Trip_Status_Eligibility__r.Active__c,Trip_Status_Eligibility__r.Start_Date__c, Trip_Status_Eligibility__r.End_Date__c FROM BTS__c WHERE Trip_Status_Eligibility__r.Active__c = true AND Account__c =: accountIdstr AND RecordType.Name = 'Broker Reward' limit 1]; } if(!BTSList.isEmpty() && BTSList[0].RecordType.Name == 'Broker Reward') { Integer additionaldays = Integer.valueOf(Label.AFocus_NewGrpNumOfDaysForRewardCal); Date grpcreatedStartDate = BTSList[0].Trip_Status_Eligibility__r.Start_Date__c - additionaldays; Date grpcreatedEndDate = BTSList[0].Trip_Status_Eligibility__r.End_Date__c + additionaldays; Map<Id,Set<Id>> grpAccMap = new Map<Id,Set<Id>>(); if(!serviceList.isEmpty()){ for(Services__c servRec : serviceList ){ if((servRec.Account__r.CreatedDate >= grpcreatedStartDate) && (servRec.Account__r.CreatedDate <= grpcreatedEndDate)) { if(!grpAccMap.containsKey(servRec.Broker_of_Record__c)){ grpAccMap.put(servRec.Broker_of_Record__c, new Set<Id>()); } grpAccMap.get(servRec.Broker_of_Record__c).add(servRec.Account__c); } } } system.debug('serviceList =' + serviceList); system.debug('grpAccMap =' + grpAccMap); if(grpAccMap != null && ! grpAccMap.isEmpty()){ if(grpAccMap.get(accountIdstr) != null){ if(grpAccMap.get(accountIdstr).size() >= 2){ wrapperobj.GrpAccts = 2; } else if(grpAccMap.get(accountIdstr).size() ==1){ wrapperobj.GrpAccts = 1; } } } else if(grpAccMap == null || grpAccMap.isEmpty()){ wrapperobj.GrpAccts = 0; } if(Club == 'premierClub' && BTSList[0].RPoints__c != null && BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c != null && BTSList[0].Trip_Status_Eligibility__c!=null){ percentage = Integer.valueOf(((BTSList[0].RPoints__c)*100) / (BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c)); wrapperobj.tPoints = Integer.valueOf(BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c); } else if(Club == 'preferredClub' && BTSList[0].RPoints__c != null && BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c != null && BTSList[0].Trip_Status_Eligibility__c!=null){ percentage = Integer.valueOf(((BTSList[0].RPoints__c)*100) / (BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c)); wrapperobj.tPoints = Integer.valueOf(BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c); } wrapperobj.rPoints = Integer.valueOf(BTSList[0].RPoints__c); wrapperobj.hasActive = BTSList[0].Trip_Status_Eligibility__r.Active__c; } wrapperobj.ViewRewards = userRec[0].ViewActivity__c; wrapperobj.perRewards= percentage; system.debug('wrapperobj' +wrapperobj); return wrapperobj; } public class demoWrapper { @AuraEnabled public Integer tPoints{get;set;} @AuraEnabled public Integer rPoints{get;set;} @AuraEnabled public Integer perRewards{get;set;} @AuraEnabled public Boolean ViewRewards{get;set;} @AuraEnabled public Boolean hasActive{get;set;} @AuraEnabled public Integer GrpAccts{get;set;} }
These lines are not covered by the above code.
for(Services__c servRec : serviceList ){ if((servRec.Account__r.CreatedDate >= grpcreatedStartDate) && (servRec.Account__r.CreatedDate <= grpcreatedEndDate)) { if(!grpAccMap.containsKey(servRec.Broker_of_Record__c)){ grpAccMap.put(servRec.Broker_of_Record__c, new Set<Id>()); } grpAccMap.get(servRec.Broker_of_Record__c).add(servRec.Account__c); } }
if(grpAccMap != null && ! grpAccMap.isEmpty()){ if(grpAccMap.get(accountIdstr) != null){ if(grpAccMap.get(accountIdstr).size() >= 2){ wrapperobj.GrpAccts = 2; } else if(grpAccMap.get(accountIdstr).size() ==1){ wrapperobj.GrpAccts = 1; } } }
- Raffus
- September 13, 2022
- Like
- 0
How to cover else part of this method in test class
This is a method in which the else part is not getting covered -
" else {
rand_App_Customer__c customer = new rand_App_Customer__c(); "
" else {
rand_App_Customer__c customer = new rand_App_Customer__c(); "
@AuraEnabled public static rand_App_Customer__c CustomerInfo(String partyId, String mobile) { try { String query = 'SELECT Id, Customer_Last_Name__c, Customer_Email__c, Nationality__c, Customer_First_Name__c, Date_of_Birth__c, Customer_Name__c, Party_Id__c FROM rand_App_Customer__c WHERE '; if (String.isNotBlank(partyId)) { query += ' Customer_Name__c != null AND Party_Id__c=:partyId'; } else if (String.isNotBlank(mobile)) { query += ' Customer_Mobile__c=:mobile'; } List<rand_App_Customer__c> customers = Database.query(query + ' LIMIT 1'); if (customers.size() > 0) { System.debug('customers ' + customers); if (String.isNotBlank(partyId)) { List<Account> accs = [SELECT Id, FirstName, LastName, email__c, Mobile__c FROM Account WHERE Party_Id__c = :partyId ORDER BY CreatedDate DESC LIMIT 1]; if (!accs.isEmpty()) { customers[0].Customer_First_Name__c = accs[0].FirstName; customers[0].Customer_Last_Name__c = accs[0].LastName; customers[0].Customer_Email__c = accs[0].email__c; customers[0].Customer_Mobile__c = accs[0].Mobile__c; customers[0].recalculateFormulas(); customers[0].Name = customers[0].Customer_Name__c; update customers[0]; } } return customers[0]; } else { rand_App_Customer__c customer = new rand_App_Customer__c(); customer.Party_Id__c = partyId; if (String.isNotBlank(partyId)) { List<Account> accs = [SELECT Id, FirstName, LastName, email__c, Mobile__c FROM Account WHERE Party_Id__c = :partyId ORDER BY CreatedDate DESC LIMIT 1]; if (!accs.isEmpty()) { customer.Customer_First_Name__c = accs[0].FirstName; customer.Customer_Last_Name__c = accs[0].LastName; customer.Customer_Email__c = accs[0].email__c; customer.recalculateFormulas(); } } customer.Customer_ID__c = String.isNotBlank(partyId) ? partyId : mobile; if (String.isNotBlank(mobile)) { customer.Customer_Mobile__c = mobile; } customer.Name = String.isBlank(customer.Customer_Name__c) ? 'User' : customer.Customer_Name__c; upsert customer Customer_ID__c; return customer; } } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }Here is my written test method
@isTest public static void getCustomerInfoTest(){ rand_App_Customer__c randCustomer = new rand_App_Customer__c(); randCustomer.Customer_ID__c = '1234567'; randCustomer.Customer_First_Name__c = 'Test rand'; randCustomer.Customer_Last_Name__c = 'Customer'; randCustomer.Party_Id__c = '8545254752'; randCustomer.Nationality__c = 'India'; // randCustomer.Date_of_Birth__c = ; randCustomer.Customer_Mobile__c = '8545254752'; randCustomer.Customer_Email__c = 'tannow@tan.ae'; Insert randCustomer; Account acc = new Account(); acc.FirstName = 'TestFname'; acc.LastName = 'TestLname'; acc.Mobile__c = '8545254752'; acc.Party_Id__c = '8545254752'; insert acc; randAppController.getCustomerInfo('8545254752', '8545254752' );
- Raffus
- September 08, 2022
- Like
- 0
How to write a test method for this
@AuraEnabled public static void saveCustomerInfo(String data, String partyId, String mobile) { rand_App_Customer__c customer = (rand_App_Customer__c) JSON.deserialize(data, rand_App_Customer__c.class); customer.Party_Id__c = String.isBlank(partyId) ? mobile : partyId; customer.Customer_ID__c = customer.Party_Id__c; customer.Customer_Mobile__c = mobile; if (String.isNotBlank(mobile)) { customer.Id = [SELECT Id FROM rand_App_Customer__c WHERE Customer_Mobile__c = :mobile LIMIT 1]?.Id; } customer.recalculateFormulas(); customer.Name = String.isBlank(customer.Customer_Name__c) ? 'User' : customer.Customer_Name__c; upsert customer Customer_ID__c; }
- Raffus
- September 08, 2022
- Like
- 0
How to write a test class for below method
@AuraEnabled public static String loadData(String strCaseInfo) { System.debug('caseInfo ' + strCaseInfo); CaseInfoWrapper caseInfo = (CaseInfoWrapper)JSON.deserialize(strCaseInfo, CaseInfoWrapper.class); rand_App_Customer__c customer = getCustomerInfo2(caseInfo.emailId); Case cse = new Case(); cse.subject = 'tan One Problem Report'; cse.Origin = rand_APP; cse.Status = 'Awaiting Approval'; cse.Priority = 'Medium'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get(rand_APP).getRecordTypeId(); cse.Description = caseInfo.description; cse.rand_App_Customer__c = customer?.Id; cse.Issue_category__c = caseInfo.category; cse.Issue_Sub_Category__c = caseInfo.subCategory; insert cse; // for skip the triggers of ContentDocumentLink && ContentDocument ContentDocumentLinkTriggerUtil.skipTrigger = true; ContentDocumentTriggerUtil.skipTrigger = true; List<ContentVersion> cVersions = new List<ContentVersion>(); for (FileInfoWrapper file : caseInfo.files) { System.debug('fileInfo ' + file); if (String.isNotBlank(file.base64Data)) { ContentVersion cv = new ContentVersion(); cv.ContentLocation = 'S'; cv.PathOnClient = file.fileName; cv.VersionData = EncodingUtil.base64Decode(file.base64Data); cv.Title = file.fileName; cVersions.add(cv); } }
- Raffus
- September 07, 2022
- Like
- 0
How to get for loop covered in test method
How to cover a for loop in this below test method
@AuraEnabled public static string getCasesData(String caseId) { try { String query = 'SELECT Id,(SELECT Id, ContentDocumentId FROM ContentDocumentLinks), CaseNumber,Issue_category__c, Issue_Sub_Category__c, rand_App_Customer__r.Party_Id__c,rand_App_Customer__r.Customer_Mobile__c, Current_Location__Latitude__s, Current_Location__Longitude__s, LocationName__c, Owner.Name, Description,CreatedDate FROM Case WHERE Id =:caseId'; query += ' ORDER BY CreatedDate DESC LIMIT 1'; List<Case> cases = Database.query(query); CaseInfoWrapper caseInfo = new CaseInfoWrapper(); set<Id> contentDocId = new set<Id>(); for (Case caseRecord : cases) { caseInfo.description = caseRecord.Description; caseInfo.longitude = caseRecord.Current_Location__Latitude__s; caseInfo.latitude = caseRecord.Current_Location__Longitude__s; caseInfo.locationName = caseRecord.LocationName__c; caseInfo.category = caseRecord.Issue_category__c; caseInfo.subCategory = caseRecord.Issue_Sub_Category__c; caseInfo.partyId = caseRecord.rand_App_Customer__r.Party_Id__c; caseInfo.mobile = caseRecord.rand_App_Customer__r.Customer_Mobile__c; if (caseRecord.ContentDocumentLinks.size() > 0) { for (ContentDocumentLink cdl : caseRecord.ContentDocumentLinks) { contentDocId.add(cdl.ContentDocumentId); } } } list<id> contectVersionID = new list<id>(); map<Id, ContentDistribution> contectDMap = new map<Id, ContentDistribution>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentDocId ORDER BY CreatedDate ASC]) { contectVersionID.add(conDistribution.ContentDocumentId); contectDMap.put(conDistribution.ContentDocumentId, conDistribution); } list<FileInfoWrapper> fileInfo = new list<FileInfoWrapper>(); caseInfo.contentDocumentIds = contectVersionID; for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); } caseInfo.files = fileInfo; System.debug('caseInfo ##' + JSON.serialize(caseInfo)); return JSON.serialize(caseInfo); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }I have written the below test class
@IsTest public static void getCasesDataTest(){ Case caseInfo = new Case(); caseInfo.description = 'test'; caseInfo.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); insert caseInfo; ContentVersion contentVersion = new ContentVersion( Title = 'Penguins', PathOnClient = 'Penguins.jpg', VersionData = Blob.valueOf('Test Content'), IsMajorVersion = true ); insert contentVersion; List<ContentDocument> documents = [ SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument ]; //create ContentDocumentLink record ContentDocumentLink cdl = New ContentDocumentLink(); cdl.LinkedEntityId = caseInfo.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; insert cdl; randAppController.getCasesData(caseInfo.id); }But not covering the for loop that is
for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); }
- Raffus
- September 07, 2022
- Like
- 0
How to write a test method for this method
@future (callout=true) public static void fetchDetailsAndUpdaterandCustomer(String emailid, String empid, String mttoken) { // rand_App_Customer__c customer = [SELECT Id,Name, Customer_Last_Name__c, Customer_Email__c, Customer_Photo_Base64__c, Customer_Emp_ID__c, Customer_First_Name__c, Customer_Name__c, Party_Id__c FROM rand_App_Customer__c WHERE Customer_Email__c= : emailid]; System.debug('customers getOrCreateCustomer' + customer); String employeeDetails = getDataFromEmployee(empid, emailid, jwttoken);//String Map<String, Object> employeeAllData = (Map<String, Object>)JSON.deserializeUntyped(employeeDetails); Map<String, Object> empCardDetails = (Map<String, Object>)employeeAllData.get('EmpCardDetailsOutputParameters'); System.debug('customers empCardDetails' + empCardDetails); If(empCardDetails != null){ Map<String, Object> p_refcur = (Map<String, Object>)empCardDetails.get('P_REFCUR'); System.debug('customers p_refcur' + p_refcur); If(p_refcur != null){ Map<String, Object> row = (Map<String, Object>)p_refcur.get('Row'); System.debug('customers row' + row); List<Object> employee = (List<Object>)row.get('Column'); for(object obj : employee){ String employeeData = JSON.serialize(obj); if(employeeData.contains('FIRST_NAME')){ customer.Customer_First_Name__c = getFieldValue(employeeData); customer.Name = customer.Customer_First_Name__c; }else if(employeeData.contains('LAST_NAME')){ customer.Customer_Last_Name__c = getFieldValue(employeeData); customer.Name = customer.Name +' '+customer.Customer_Last_Name__c; }else if(employeeData.contains('EMPLOYEE_PHOTO')){ String empPhoto = getFieldValue(employeeData); String empPhotoFinal = empPhoto.replaceAll('\n', ''); customer.Customer_Photo_Base64__c = 'data:image/jpeg;base64,'+empPhotoFinal; }else if(employeeData.contains('DEPARTMENT')){ customer.Customer_Department__c = getFieldValue(employeeData); } } } } customer.recalculateFormulas(); System.debug('before upsert FromFuture customer ' + customer); upsert customer; } }
- Raffus
- September 06, 2022
- Like
- 0
How to write a test method content document
@AuraEnabled
public static FileInfoWrapper createPublicUrl(String fileData) {
try {
FileInfoWrapper file = (FileInfoWrapper)JSON.deserialize(fileData, FileInfoWrapper.class);
if (String.isNotBlank(file.base64Data)) {
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = file.fileName;
cv.VersionData = EncodingUtil.base64Decode(file.base64Data);
cv.Title = file.fileName;
insert cv;
ContentDistribution cd = new ContentDistribution();
cd.Name = file.fileName;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowViewInBrowser = true;
cd.PreferencesLinkLatestVersion = true;
cd.PreferencesNotifyOnVisit = false;
cd.PreferencesPasswordRequired = false;
cd.PreferencesAllowOriginalDownload = true;
insert cd;
cd = [SELECT Id, ContentVersionId, ContentDownloadUrl FROM ContentDistribution WHERE Id = :cd.Id];
file.publicUrl = cd.ContentDownloadUrl;
file.contentDistributionId = cd.Id;
file.contentVersionId = cd.ContentVersionId;
return file;
}
else {
return file;
}
}
public static FileInfoWrapper createPublicUrl(String fileData) {
try {
FileInfoWrapper file = (FileInfoWrapper)JSON.deserialize(fileData, FileInfoWrapper.class);
if (String.isNotBlank(file.base64Data)) {
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = file.fileName;
cv.VersionData = EncodingUtil.base64Decode(file.base64Data);
cv.Title = file.fileName;
insert cv;
ContentDistribution cd = new ContentDistribution();
cd.Name = file.fileName;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowViewInBrowser = true;
cd.PreferencesLinkLatestVersion = true;
cd.PreferencesNotifyOnVisit = false;
cd.PreferencesPasswordRequired = false;
cd.PreferencesAllowOriginalDownload = true;
insert cd;
cd = [SELECT Id, ContentVersionId, ContentDownloadUrl FROM ContentDistribution WHERE Id = :cd.Id];
file.publicUrl = cd.ContentDownloadUrl;
file.contentDistributionId = cd.Id;
file.contentVersionId = cd.ContentVersionId;
return file;
}
else {
return file;
}
}
- Raffus
- September 06, 2022
- Like
- 0
How to write test test method for below code
@AuraEnabled public static String loadData(String strCaseInfo) { System.debug('caseInfo ' + strCaseInfo); CaseInfoWrapper caseInfo = (CaseInfoWrapper)JSON.deserialize(strCaseInfo, CaseInfoWrapper.class); //rand_App_Customer__c customer = getCustomerInfo(caseInfo.partyId, caseInfo.mobile); rand_App_Customer__c customer = getCustomerInfo2(caseInfo.emailId); Case cse = new Case(); cse.subject = 'tan One Problem Report'; cse.Origin = rand_APP; cse.Status = 'Awaiting Approval'; cse.Priority = 'Medium'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get(rand_APP).getRecordTypeId(); // cse.Hex_Service_Request__c = 'System Update'; // cse.Hex_Service_Request_new__c = 'System Update'; // cse.ProblemCode__c = 'NOC for Name Addition - HO'; cse.Description = caseInfo.description; //RN Comment //cse.Current_Location__Latitude__s = caseInfo.latitude; //cse.Current_Location__Longitude__s = caseInfo.longitude; cse.rand_App_Customer__c = customer?.Id; //cse.LocationName__c = caseInfo.locationName; */ cse.Issue_category__c = caseInfo.category; cse.Issue_Sub_Category__c = caseInfo.subCategory; insert cse; // for skip the triggers of ContentDocumentLink && ContentDocument ContentDocumentLinkTriggerUtil.skipTrigger = true; ContentDocumentTriggerUtil.skipTrigger = true; List<ContentVersion> cVersions = new List<ContentVersion>(); for (FileInfoWrapper file : caseInfo.files) { System.debug('fileInfo ' + file); if (String.isNotBlank(file.base64Data)) { ContentVersion cv = new ContentVersion(); cv.ContentLocation = 'S'; cv.PathOnClient = file.fileName; cv.VersionData = EncodingUtil.base64Decode(file.base64Data); cv.Title = file.fileName; cVersions.add(cv); } } List<Id> contentDocumentIds = new List<Id>(caseInfo.contentDocumentIds); if (cVersions.size() > 0) { insert cVersions; List<ContentDistribution> ContentDistributionList = new List<ContentDistribution>(); for(ContentVersion ctv : cVersions){ ContentDistribution cd = new ContentDistribution(); cd.Name = ctv.Title; cd.ContentVersionId = ctv.Id; cd.PreferencesAllowViewInBrowser = true; cd.PreferencesLinkLatestVersion = true; cd.PreferencesNotifyOnVisit = false; cd.PreferencesPasswordRequired = false; cd.PreferencesAllowOriginalDownload = true; ContentDistributionList.add(cd); } if(ContentDistributionList.size() > 0){ INSERT ContentDistributionList; } Set<Id> cvIds = new Map<Id, ContentVersion>(cVersions).keySet(); for (ContentVersion cVersion : [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN:cvIds ORDER BY CreatedDate ASC]) { contentDocumentIds.add(cVersion.ContentDocumentId); } } List<ContentDocumentLink> links = new List<ContentDocumentLink>(); for (Id contentDocumentId : contentDocumentIds) { ContentDocumentLink link = new ContentDocumentLink(); link.LinkedEntityId = cse.Id; link.ContentDocumentId = contentDocumentId; link.ShareType = 'V'; links.add(link); } insert links; return [SELECT CaseNumber FROM Case WHERE Id = :cse.Id]?.CaseNumber; }Please help me to write a test method for the above method.
- Raffus
- September 06, 2022
- Like
- 0
How to write a test method for related objects
@AuraEnabled public static List<CaseResultWrapper> getCases(String emailid) { try { List<CaseResultWrapper> result = new List<CaseResultWrapper>(); List<String> caseStatuses = new List<String>{'Approved', 'Awaiting Approval', 'Rejected'}; String query = 'SELECT Id,CaseNumber, Issue_category__c, Points__c, Issue_Sub_Category__c, (SELECT Id, ContentDocumentId FROM ContentDocumentLinks WHERE ContentDocument.FileType != \'wav\'), Status, Country__c, Owner.Name, Description,CreatedDate FROM Case WHERE RecordType.DeveloperName= :rand_APP AND rand_App_Customer__r.Customer_Email__c !=null AND status IN :caseStatuses'; if (String.isNotBlank(emailid)) { query += ' AND rand_App_Customer__r.Customer_Email__c=:emailid'; } /*else if (String.isNotBlank(mobile)) { query += 'AND rand_App_Customer__r.Customer_Mobile__c=:mobile'; } else { query += 'AND Id = null'; }*/ query += ' ORDER BY CreatedDate DESC LIMIT 50'; //CreatedDate = THIS_QUARTER System.debug('getCases query '+query); List<Case> cases = Database.query(query); Map<Id, Case> contentCaseMap = new Map<Id, Case>(); for (Case caseRecord : cases) { if (caseRecord.ContentDocumentLinks.size() > 0 && caseRecord.ContentDocumentLinks[0].ContentDocumentId != null) { contentCaseMap.put(caseRecord.ContentDocumentLinks[0].ContentDocumentId, caseRecord); } else { contentCaseMap.put(caseRecord.Id, caseRecord); } } Map<Id, String> contentUrlMap = new Map<Id, String>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentCaseMap.keySet() ORDER BY CreatedDate ASC]) { contentUrlMap.put(conDistribution.ContentDocumentId, conDistribution.ContentDownloadUrl); } for (Id contentId : contentCaseMap.keySet()) { CaseResultWrapper caseWrp = new CaseResultWrapper(); caseWrp.contentDocId = contentId; caseWrp.caseRecord = contentCaseMap.get(contentId); caseWrp.imageUrl = contentUrlMap.get(contentId); caseWrp.categoryLogoUrl =''; DateTime dT = contentCaseMap.get(contentId).CreatedDate; If(dT.month()==1){ caseWrp.createdDate = dT.day()+'-Jan-'+dT.year(); } If(dT.month()==2){ caseWrp.createdDate = dT.day()+'-Feb-'+dT.year(); } If(dT.month()==3){ caseWrp.createdDate = dT.day()+'-Mar-'+dT.year(); } If(dT.month()==4){ caseWrp.createdDate = dT.day()+'-Apr-'+dT.year(); } If(dT.month()==5){ caseWrp.createdDate = dT.day()+'-May-'+dT.year(); } If(dT.month()==6){ caseWrp.createdDate = dT.day()+'-Jun-'+dT.year(); } If(dT.month()==7){ caseWrp.createdDate = dT.day()+'-Jul-'+dT.year(); } If(dT.month()==8){ caseWrp.createdDate = dT.day()+'-Aug-'+dT.year(); } If(dT.month()==9){ caseWrp.createdDate = dT.day()+'-Sep-'+dT.year(); } If(dT.month()==10){ caseWrp.createdDate = dT.day()+'-Oct-'+dT.year(); } If(dT.month()==11){ caseWrp.createdDate = dT.day()+'-Nov-'+dT.year(); } If(dT.month()==12){ caseWrp.createdDate = dT.day()+'-Dec-'+dT.year(); } result.add(caseWrp); } return result; }The parameter that i have passed that is email is not in case object but in rand_App_Customer__c object- and case child object of rand_App_Customer__c object- so how i can give the parameter for this method
Below is my test method
@IsTest public static void getCasesTest(){ // Id rand_AppRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('rand_App').getRecordTypeId(); rand_App_Customer__c randCustomer = new rand_App_Customer__c(); randCustomer.Customer_ID__c = '1234567'; randCustomer.Customer_Email__c = 'tannow@tan.ae'; insert randCustomer; Case cse = new Case(); cse.Issue_Sub_Category__c = 'Test category'; cse.Status = 'Approved'; cse.Description = 'Test'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); cse.rand_App_Customer__c = randCustomer.Id; insert cse; List<ContentDocument> documents = [SELECT Id,title,LatestPublishedVersionId FROM ContentDocument]; ContentDocumentLink cdl = new ContentDocumentLink(); cdl.LinkedEntityId = cse.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; // cdl.FileType = 'jpg'; insert cdl; randAppController.getCases('tannow@tan.ae'); }
- Raffus
- September 05, 2022
- Like
- 0
How to write a test method for related objects with wrapper class in it.
I am not understanding what and how to put data for the below method
Please help...
@AuraEnabled public static string getCasesData(String caseId) { try { String query = 'SELECT Id,(SELECT Id, ContentDocumentId FROM ContentDocumentLinks), CaseNumber,Issue_category__c, Issue_Sub_Category__c, rand_App_Customer__r.Party_Id__c,rand_App_Customer__r.Customer_Mobile__c, Current_Location__Latitude__s, Current_Location__Longitude__s, LocationName__c, Owner.Name, Description,CreatedDate FROM Case WHERE Id =:caseId'; query += ' ORDER BY CreatedDate DESC LIMIT 1'; List<Case> cases = Database.query(query); CaseInfoWrapper caseInfo = new CaseInfoWrapper(); set<Id> contentDocId = new set<Id>(); for (Case caseRecord : cases) { caseInfo.description = caseRecord.Description; caseInfo.longitude = caseRecord.Current_Location__Latitude__s; caseInfo.latitude = caseRecord.Current_Location__Longitude__s; caseInfo.locationName = caseRecord.LocationName__c; caseInfo.category = caseRecord.Issue_category__c; caseInfo.subCategory = caseRecord.Issue_Sub_Category__c; caseInfo.partyId = caseRecord.rand_App_Customer__r.Party_Id__c; caseInfo.mobile = caseRecord.rand_App_Customer__r.Customer_Mobile__c; if (caseRecord.ContentDocumentLinks.size() > 0) { for (ContentDocumentLink cdl : caseRecord.ContentDocumentLinks) { contentDocId.add(cdl.ContentDocumentId); } } } list<id> contectVersionID = new list<id>(); map<Id, ContentDistribution> contectDMap = new map<Id, ContentDistribution>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentDocId ORDER BY CreatedDate ASC]) { contectVersionID.add(conDistribution.ContentDocumentId); contectDMap.put(conDistribution.ContentDocumentId, conDistribution); } list<FileInfoWrapper> fileInfo = new list<FileInfoWrapper>(); caseInfo.contentDocumentIds = contectVersionID; for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); } caseInfo.files = fileInfo; System.debug('caseInfo ##' + JSON.serialize(caseInfo)); return JSON.serialize(caseInfo); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }So far I have written below myself as per my understanding but it is not giving coverage after "for (Case case record : cases)".
@IsTest public static void getCasesDataTest(){ Case caseInfo = new Case(); caseInfo.description = 'test'; caseInfo.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); insert caseInfo; ContentVersion contentVersion = new ContentVersion( Title = 'Penguins', PathOnClient = 'Penguins.jpg', VersionData = Blob.valueOf('Test Content'), IsMajorVersion = true ); insert contentVersion; List<ContentDocument> documents = [ SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument ]; //create ContentDocumentLink record ContentDocumentLink cdl = New ContentDocumentLink(); cdl.LinkedEntityId = caseInfo.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; insert cdl; randAppController.CaseInfoWrapper wrapper= new randAppController.CaseInfoWrapper(); wrapper.category = 'Emaar Gift Card'; wrapper.subCategory = 'EGC - Card Error/Machine Network Failure'; wrapper.partyId = '1234'; wrapper.mobile = '7894561230'; randAppController.getCasesData('5003M038208iGzOLOU'); }
Please help...
- Raffus
- September 05, 2022
- Like
- 0
Aura component for updating the Status field of custom object.
I need to update the status(ak2397__Status__c) picklist field of the Custom Orders(ak2397__Orders__c) object using a lightning button. I have created a button 'cancel' and 'reorder'. If I click the cancel button then the status of the object should change from 'Ordered' to 'Cancelled' and if I click the reorder button then the status should change from 'Cancelled to 'Ordered'. I am stuck pls help.
Here is my complete code
Component----
Helper
Apex Controller
Here is my complete code
Component----
<aura:component controller="TestForOMapex" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" > <aura:attribute name="accList" type="List"/> <aura:attribute name="activeSections" type="List" /> <aura:attribute name="searchResult" type="List" description="use for store and display account list return from server"/> <aura:attribute name="searchKeyword" type="String" description="use for store user search input"/> <aura:handler name="init" value="{!this}" action="{!c.doinit}"/> <lightning:card title="Customer Order Details" iconName="standard:Contact"> <div class="slds-border_bottom"> </div> <div class="slds-scrollable_y"> <lightning:layoutItem size="12"> <div class="slds-text-longform"> <lightning:input value="{!v.searchKeyword}" placeholder="Search Customers" aura:id="searchField" name="searchField" onchange="{!c.onChange1 }"/> <br/> </div> </lightning:layoutItem> </div> <div class="slds-align_absolute-center"> <table class="slds-table slds-table_cell-buffer slds-table_bordered"> <thead> <tr class="slds-line-height_reset"> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order ID">Order ID</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Orders">Food Item</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Order Details</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Order Date</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Status</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Edit">Cancel</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Edit">ReOrder</div> </th> </tr> </thead> <br/> <tbody> <aura:iteration items="{!v.accList}" var="acc" indexVar="index"> <tr class="slds-line-height_reset"> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="FirstName">{!acc.ak2397__Order_Id__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Food Item"> {!acc.ak2397__Food_Item__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order Detail">{!acc.ak2397__Order_Details__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order Date">{!acc.CreatedDate}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Status">{!acc.ak2397__Status__c}</div> </td> <td data-label="icon" class="slds-col slds-size_1-of-12" onclick="{!c.cancel}" id="{!acc.Id}"> <lightning:icon iconName="utility:delete" size="small" /> </td> <td data-label="icon" class="slds-col slds-size_1-of-12" onclick="{!c.reorder}" id="{!acc.Id}"> <lightning:icon iconName="utility:change_record_type" size="small" /> </td> </tr> </aura:iteration> </tbody> </table> </div> </lightning:card> </aura:component>Js Controller
({ onChange1: function (component, evt, helper) { var selectedLimit = component.find('searchField').get('v.value'); component.set('v.searchKeyword', selectedLimit); helper.SearchHelper(component, event); }, doinit: function(component) { var action = component.get('c.getContactData'); var self = this; action.setCallback(this, function(actionResult) { component.set('v.acclist', actionResult.getReturnValue()); }); $A.enqueueAction(action); }, cancel : function(component, event) { var action = component.get("c.cancelContact"); action.setParams({contactId:event.target.id}); action.setCallback(this, function(response) { component.set("v.accList",response.getReturnValue()); }); $A.enqueueAction(action); }, reorder : function(component, event) { var action = component.get("c.updateContact"); action.setParams({contactId:event.target.id}); action.setCallback(this, function(response) { component.set("v.accList",response.getReturnValue()); }); $A.enqueueAction(action); }, })
Helper
({ SearchHelper : function(component, event, helper) { var action = component.get('c.fetchAcc'); action.setParams({ searchKey : component.get("v.searchKeyword"), }); action.setCallback(this, function(response){ var state = response.getState(); if(state === "SUCCESS"){ var allValues = response.getReturnValue(); console.log("allValues--->>> " + JSON.stringify(allValues)); //component.set('v.activeSections', allValues.Name); component.set('v.accList', allValues); } else if(state === "ERROR") { var errors = response.getError(); if(errors){ if(errors[0] && errors[0].message){ console.log("Error Message: " + errors[0].message); } } else{ console.log("Unknown Error"); } } }); $A.enqueueAction(action); } });
Apex Controller
public class TestForOMapex { @AuraEnabled(cacheable=true) public static List<ak2397__Orders__c> fetchAcc (String searchKey){ String query= 'select ak2397__Order_Id__c, ak2397__Food_Item__c, ak2397__Order_Details__c, CreatedDate, ak2397__Status__c from ak2397__Orders__c'; if ( searchKey != Null ) { String key = '%' + searchKey + '%'; query += ' WHERE Name LIKE :key'; }system.debug(Database.query( query )); return Database.query( query ); } @AuraEnabled public static List<ak2397__Orders__c> getContactData(){ return [select Id from ak2397__Orders__c Limit 10]; } @AuraEnabled public static List<ak2397__Orders__c> cancelContact(String contactId) { List<ak2397__Orders__c> upContact = [SELECT Id, ak2397__Status__c FROM ak2397__Orders__c]; if(upContact.size()>0){ for(ak2397__Orders__c om: upContact){ om.ak2397__Status__c = 'Cancelled'; upContact.add(om); } upsert upContact; } return getContactData(); public static List<ak2397__Orders__c> updateContact(String contactId) { List<ak2397__Orders__c> upContact = [SELECT Id, ak2397__Status__c FROM ak2397__Orders__c]; if(upContact.size()>0){ for(ak2397__Orders__c om: upContact){ om.ak2397__Status__c = 'Ordered'; upContact.add(om); } upsert upContact; } return getContactData(); } } }
- Raffus
- July 05, 2022
- Like
- 0
Write a test class for this class for getting full coverage.
This UserMigrationRoute class is migration Community profile users to Partner profile users and saving their username Password in userMigration object. I have really hard time writing test classes. i have written Test class but don't know exactly how i can get full coverage. pls, help....
I am getting 65 percent coverage!
Line 48-77 is not covered (Boolean isSUccess=createUserMigration('',objUser[0],'');) to (return maprespone;)
Main class
Test class
I am getting 65 percent coverage!
Line 48-77 is not covered (Boolean isSUccess=createUserMigration('',objUser[0],'');) to (return maprespone;)
Main class
public class UserMigrationRoute extends BaseRoute{ public override Object doPost() { List<String> allowhosts=Label.Host_Name.split(','); Map<String,object> maprespone=new Map<String,object>(); system.debug('Hi'); if(String.isNotBlank(request.headers.get('Host')) && String.isNotBlank(request.headers.get('Host')) && !allowhosts.contains(request.headers.get('Host'))){ setResponseMessage('Invalid Host Header',ConstantsUtils.ERROR_CODE); return null; } if(this.request.headers.get('Content-Type')!=null && this.request.headers.get('Content-Type').substringAfter('/').equalsIgnoreCase('xml')){ setResponseMessage('Request in '+request.headers.get('Content-Type').substringAfter('/')+' format. Please provide request in json format.',ConstantsUtils.ERROR_CODE); return null; } map<String,object> data=this.getBodyJSON(); string id=(string)data.get('userId'); Map<String,String> mapofPartnerRecordType=new Map<String,String>(); List<User> objUser; try{ objUser=[SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null and id=:id]; if(objUser==null || objUser.size()==0){ setResponseMessage('Invalid uesrId, Please provide community user id',ConstantsUtils.ERROR_CODE); return null; } List<Account> lstAccount=new List<Account>(); if(!objUser[0].Account.IsPartner){ Account account=new Account(); account.Id=objUser[0].AccountId; account.IsPartner=true; lstAccount.add(account); // update lstAccount; //commented by shabnoor for testing } if(mapOfCustomerAndPartner.containsKey(objUser[0].profile.Name)){ String partnerProfile=mapOfCustomerAndPartner.get(objUser[0].profile.Name); objUser[0].ProfileId=[Select Id , Name from profile where Name= :partnerProfile].Id; } update objUser[0]; Boolean isSUccess=createUserMigration('',objUser[0],''); if(isSUccess){ maprespone.put('statuscode',1); maprespone.put('statusmessage','user migration successfully done'); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage','user migration failed'); return maprespone; } catch(DMLException ex){ if(ex.getDmlType(0)==StatusCode.DUPLICATE_USERNAME){ String charString = '!@#$%^&*()nopqrstuvwABCDPQRSTUVWXYZ0123456789abcdefghijkEFGHIJKLMNOlmxyz'; String randomNew = ''; while (randomNew .length() < 8){ Integer changeInt = Math.mod(Math.abs(Crypto.getRandomInteger()), charString.length()); randomNew += charString.substring(changeInt , changeInt +1); } Boolean isSUccess=createUserMigration(objUser[0].userName.replace('@',DateTime.now().millisecond() +'@'),objUser[0],randomNew); if(isSUccess){ system.setPassword(objUser[0].Id, randomNew); maprespone.put('statuscode',1); maprespone.put('statusmessage','user migration successfully done'); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); } catch(Exception ex){ maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); return maprespone; } return maprespone; } public void setResponseMessage(String strMessge,String strCode){ response.addHeader('Content-Type', 'application/json'); response.responseBody = Blob.valueOf( '[{"message":' + strMessge + ',"errorCode":'+ strCode + '}]' ); response.statusCode = 400; } public Boolean createUserMigration(String Newusername,User objUser,String tempPassword){ try{ UserMigration__c UserMigration=new UserMigration__c(); // UserMigration.Newusername__c=objUser.userName; if(String.isNotBlank(Newusername)){ UserMigration.Newusername__c=Newusername; } UserMigration.OlduserName__c=objUser.userName; UserMigration.User__c=objUser.id; if(String.isNotBlank(tempPassword)){ UserMigration.tempPassword__c= tempPassword; } insert UserMigration; return true; }catch(Exception ex){ return false; } } public map<String,String> mapOfCustomerAndPartner=new Map<String,String>{ 'Customer Community - Admin'=>'Partner Community - Admin', 'Customer Community - Agent'=>'Partner Community - Agent', 'Customer Community - Agent + Admin'=>'Partner Community - Agent + Admin', 'Customer Community - Auth + Admin'=>'Partner Community - Auth + Admin', 'Customer Community - Auth + Admin + Agent'=>'Partner Community - Auth + Admin + Agent', 'Customer Community - Auth + Agent'=>'Partner Community - Auth + Agent', 'Customer Community - Auth Officer'=>'Partner Community - Auth Officer', 'Customer Community - Customer Direct User'=>'Partner Community - Customer Direct User', 'Customer Community - Owner'=>'Partner Community - Owner', 'Customer Community Plus User'=>'Partner Community - Admin', 'Customer Direct Guest'=>'Partner Direct Guest' }; }
Test class
public with sharing class UserMigrationRouteTest { @testSetup static void setup() { Broker_App_Settings__c BAS = new Broker_App_Settings__c( General_Partner_User_Id__c = '0054H0000067b6o', ApiToken__c = '6e9bece1914809fb8493146417e722f6', IVector__c = 'FFFFFFFFFFFFFFFF', Key__c = 'x/A%D*G-KaPdSgVkYp3s6v9y&B&E(H+M', General_Partner_User_Name__c = 'qaqqqqqqqqqqqqqq.com' ); insert BAS; TestDataSetup.createIntegrationCustomSettingsData(); TestDataSetup.createTriggerSettingsData(); TestDataSetup.createAppSettingsData(); Account partnerAccount = TestDataSetup.createAgencyAccount(); insert partnerAccount; Contact objAgencyContact = TestDataSetup.createAgentContact( partnerAccount.Id ); objAgencyContact.RERA_Card_No__c = '123456'; objAgencyContact.Sys_Agent_Representative__c = true; insert objAgencyContact; Profile portalProfile = [ SELECT Id FROM Profile WHERE Name = 'Sales Partner Community User' LIMIT 1 ]; User objPartnerUser = new User( Username = System.now().millisecond() + 'test999@test.com', ContactId = objAgencyContact.Id, ProfileId = portalProfile.Id, Alias = 'pTst', Email = 'testingisgoingon999@test.com', EmailEncodingKey = 'UTF-8', LastName = 'Con', CommunityNickname = 'test999', TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', LanguageLocaleKey = 'en_US' ); Database.insert(objPartnerUser); } static testMethod void verifyContentType() { User objPartnerUser = [ SELECT Id, Username FROM User WHERE email = 'testingisgoingon999@test.com' ]; System.runAs(objPartnerUser) { String requestURI = '/userprofileupdate/'; String RESOURCE_PATH = '/services/apexrest' + requestURI; map<String, String> headers = new Map<String, String>(); headers.put('Content-Type', 'application/json'); headers.put('Host', 'www.gmail1.com'); Broker_App_Settings__c BAS = Broker_App_Settings__c.getOrgDefaults(); headers.put('apikey', BAS.ApiToken__c); Map<String, String> requestData = new Map<string, string>(); String JsonRecord = Json.serialize(requestData); setRestCall(RESOURCE_PATH, requestURI, 'POST', headers, null, JsonRecord); try { RestResponse resp = RestContext.Response; UserMigrationResource.handlePost(); resp = RestContext.Response; } catch (exception ex) { } } } static testMethod void createMigrationUserNegative(){ List<User> objUser = [SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null]; UserMigrationRoute mem = new UserMigrationRoute(); Boolean isSUccess = mem.createUserMigration('newusername123',objUser[0],'newpassword1234'); System.assertEquals(false,isSUccess, 'Result'); } static testMethod void createMigrationPositive(){ List<User> objUser = [SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null]; UserMigrationRoute mem = new UserMigrationRoute(); Boolean isSUccess = mem.createUsermigration('',objUser[0],''); System.assertEquals(true,isSUccess,'result'); } static testMethod void verifydoPost() { User objPartnerUser = [ SELECT Id, Username FROM User WHERE email = 'testingisgoingon999@test.com' ]; System.runAs(objPartnerUser) { CaseTriggerHandler.TriggerDisabled = true; String requestURI = '///userprofileupdate/'; String RESOURCE_PATH = '/services/apexrest' + requestURI; map<String, String> headers = new Map<String, String>(); Broker_App_Settings__c BAS = Broker_App_Settings__c.getOrgDefaults(); headers.put('apikey', BAS.ApiToken__c); Map<String, String> requestData = new Map<string, string>(); requestData.put('userId', '0053M000001YvnTQAS'); String JsonRecord = Json.serialize(requestData); setRestCall(RESOURCE_PATH, requestURI, 'POST', headers, null, JsonRecord); try { RestResponse resp = RestContext.Response; UserMigrationResource.handlePost(); resp = RestContext.Response; //System.assertEquals(1,resp.statusCode,'success'); //Assert with expected status code. } catch (exception ex) { } } } public static void setRestCall( String resourcePath, String requestURI, String method, map<String, String> headers, map<String, String> paraMeters, String body ) { RestRequest req = new RestRequest(); req.requestURI = requestURI; req.resourcePath = resourcePath; req.httpMethod = method; if (String.isNotEmpty(body)) { req.requestBody = Blob.valueOf(body); } if (headers != null && headers.size() > 0) { req.headers.putAll(headers); } if (paraMeters != null && paraMeters.size() > 0) { req.params.putAll(paraMeters); } system.debug('test' + req); RestContext.Request = req; RestContext.Response = new RestResponse(); } }
- Raffus
- June 21, 2022
- Like
- 0
Not able to cover this line of code, enrollmentsId are not inserted
This is method
This mine test method
public static void carriersBMLLUpdatecreateCaseComments(List<Enrollment__c> newList,Map<Id,Enrollment__c> oldMap) { Set<Id> enrollmentIds = new Set<Id>(); Map<Id, Enrollment__c> newMap = new Map<Id, Enrollment__c>(newList); for(Enrollment__c enrollment: newList) { //on update if(oldMap!=null) { if(enrollment.Enrollment_Method__c == Label.AFocus_ThirdParty_PickVal){ if(enrollment.Carriers_BMLL_will_not_be_the_GA__c !=null && enrollment.Carriers_BMLL_will_not_be_the_GA__c != oldMap.get(enrollment.Id).Carriers_BMLL_will_not_be_the_GA__c) { enrollmentIds.add(enrollment.Id); } } } //on insert else if(oldMap==null){ if(enrollment.Enrollment_Method__c == Label.AFocus_ThirdParty_PickVal){ if(enrollment.Carriers_BMLL_will_not_be_the_GA__c == null || enrollment.Carriers_BMLL_will_not_be_the_GA__c =='') { enrollmentIds.add(enrollment.Id); } } } } System.debug('enrollmentIds are'+enrollmentIds); List<Case> enrollmentCases = new List<Case>(); List<CaseComment> CaseCommentsList = new List<CaseComment>(); if(enrollmentIds.size()>0) { enrollmentCases = [Select Id,Enrollment__c,Enrollment__r.Carriers_BMLL_will_not_be_the_GA__c,Enrollment__r.Enrollment_Method__c from Case where Enrollment__c IN :enrollmentIds AND Recordtype.Name = :Label.AFocus_New_Business_Case]; if(enrollmentCases.size()>0) { for(Case enrollemtCase:enrollmentCases) { CaseComment caseComment = new CaseComment(); caseComment.ParentId = enrollemtCase.Id; caseComment.IsPublished = false; caseComment.CommentBody = 'ATTN:New Business Team Carriers BMLL will not be the GA:['+ enrollemtCase.Enrollment__r.Carriers_BMLL_will_not_be_the_GA__c +'] When Services are created for this Carriers add $0 in SCA PEPM field on each Service'; CaseCommentsList.add(caseComment); } } } System.debug('CaseCommentsList is :' + CaseCommentsList); try{ if(!CaseCommentsList.isEmpty()){ insert CaseCommentsList; } } catch(Exception ex){ // ExceptionHandlerController.logErrorsInboundAPI('Sync BenAdminBuildCase Notes with Enrollment Notes','AFocus_EnrollmentTriggerHandler','updatecaseNotesFromEnrollmentNotes',ex.getMessage(),'Case ids to be updated' +caseUpdatedList,'Exception occurred during updating status',UserInfo.getUserId(),'Error'); ExceptionHandlerController.logErrorsInboundAPI('Create Case Comments when Carriers_BMLL_will_not_be_the_GA__c is updated','AFocus_EnrollmentTriggerHandler','carriersBMLLUpdatecreateCaseComments',ex.getMessage(),'Carriers_BMLL_will_not_be_the_GA__c to be updated' +CaseCommentsList,'Exception occurred during updating Carriers_BMLL_will_not_be_the_GA__c',UserInfo.getUserId(),'Error'); } }
This mine test method
@isTest static void carriersBMLLUpdatecreateCaseCommentsTest(){ Set<Id> enrollmentIds = new Set<Id>(); string Id =[SELECT id from RecordType where Name ='Agency'].Id; Account Acc1 = new Account(); Acc1.Name = 'Test Account forth'; Acc1.Email__c='testtest@gmail.com'; Acc1.Source_System__c ='BenefitPoint'; Acc1.Technology_Adoption__c ='Low - Not Open'; Acc1.RecordTypeId = Id; insert Acc1; System.debug('Account info: ' + Acc1); List<Enrollment__c> enlist = new List<Enrollment__c>(); Enrollment__c en1 = new Enrollment__c(); en1.Broker__c= Acc1.id; en1.Status__c='Not Submitted'; en1.Notes__c='Test Notes'; en1.Plan_Selection_Complete__c= true; en1.Street__c = 'eStreet'; en1.city__c = 'New york'; en1.State__c = 'NY'; en1.Zip__c = '48979842'; en1.Effective_Date__c = system.today(); en1.Client_Type_Status__c = 'Group'; en1.EIN__c = '281764'; en1.Phone__c = '(555) 123-4567'; en1.Full_Time_Employees__c = 80; en1.Enrollment_Method__c='Third-party'; en1.Carriers_BMLL_will_not_be_the_GA__c ='test'; insert en1; enlist.add(en1); //insert enlist; System.debug('Enrollment1 info: ' + en1); enrollmentIds.add(en1.Id); Map<Id,Enrollment__c> eListMap = new Map<Id,Enrollment__c>(); eListMap.put(en1.Id,en1); system.debug('elistMap '+ eListMap); Id RTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Benefit New Business / Renewal').getRecordTypeId(); case caseRec=new case(); caseRec.RecordTypeId = RTypeId; caseRec.Origin='Sales Escalation'; caseRec.SuppliedEmail='test1234@test1234.com'; caseRec.Reason='APS'; caseRec.subject='Installation Problem'; //caseRec.AccountId=accGpRec.id; caseRec.Status = 'New'; caseRec.Approval_Status__c = 'Not Submitted'; //caseRec.NBA_Rep__c = UserInfo.getUserId(); caseRec.Enrollment__c = en1.Id; insert caseRec; System.debug('Case1 info: ' + caseRec); CaseComment comment1 = new CaseComment(); comment1.ParentId = caseRec.Id; comment1.CommentBody = 'Case record 1 comment'; comment1.IsPublished = TRUE; insert comment1; System.debug('Case comment ' + comment1); AFocus_EnrollmentTriggerHandler.carriersBMLLUpdatecreateCaseComments(enlist,eListMap); }
- Raffus
- October 01, 2022
- Like
- 0
Written a test class but few Lines are not covered?
I have written a test class but a few lines are not covered. I do not understand how to cover it. Please help!!!
These lines are not covered by the above code.
@AuraEnabled public static demoWrapper getData(String Club){ String userId= User.getLoggedInUserId(); List<User> userRec = [Select Id, Name,accountId,ContactId,ViewActivity__c from User where Id =: userId]; List<BTS__c> BTSList = new List<BTS__c>(); List<Services__c> serviceList = new List<Services__c>(); Integer percentage = 0; demoWrapper wrapperobj = new demoWrapper(); String accountIdstr = userRec[0].accountId; if(accountIdstr <> null && accountIdstr != ''){ serviceList = [Select id, Account__c,Account__r.RecordType.Name,Account__r.CreatedDate,Broker_of_Record__c, Broker_of_Record__r.Club__c from Services__c where Broker_of_Record__c =: accountIdstr AND Account__r.RecordType.Name = 'Group']; BTSList = [Select id, name, RPoints__c,Milestone_Date__c,RecordType.Name,Trip_Status_Eligibility__r.Pinnacle_Target_Points__c,Trip_Status_Eligibility__r.RecordType.Name, Trip_Status_Eligibility__r.Premier_Target_Points__c,Trip_Status_Eligibility__r.Preferred_Target_Points__c, Trip_Status_Eligibility__r.Active__c,Trip_Status_Eligibility__r.Start_Date__c, Trip_Status_Eligibility__r.End_Date__c FROM BTS__c WHERE Trip_Status_Eligibility__r.Active__c = true AND Account__c =: accountIdstr AND RecordType.Name = 'Broker Reward' limit 1]; } if(!BTSList.isEmpty() && BTSList[0].RecordType.Name == 'Broker Reward') { Integer additionaldays = Integer.valueOf(Label.AFocus_NewGrpNumOfDaysForRewardCal); Date grpcreatedStartDate = BTSList[0].Trip_Status_Eligibility__r.Start_Date__c - additionaldays; Date grpcreatedEndDate = BTSList[0].Trip_Status_Eligibility__r.End_Date__c + additionaldays; Map<Id,Set<Id>> grpAccMap = new Map<Id,Set<Id>>(); if(!serviceList.isEmpty()){ for(Services__c servRec : serviceList ){ if((servRec.Account__r.CreatedDate >= grpcreatedStartDate) && (servRec.Account__r.CreatedDate <= grpcreatedEndDate)) { if(!grpAccMap.containsKey(servRec.Broker_of_Record__c)){ grpAccMap.put(servRec.Broker_of_Record__c, new Set<Id>()); } grpAccMap.get(servRec.Broker_of_Record__c).add(servRec.Account__c); } } } system.debug('serviceList =' + serviceList); system.debug('grpAccMap =' + grpAccMap); if(grpAccMap != null && ! grpAccMap.isEmpty()){ if(grpAccMap.get(accountIdstr) != null){ if(grpAccMap.get(accountIdstr).size() >= 2){ wrapperobj.GrpAccts = 2; } else if(grpAccMap.get(accountIdstr).size() ==1){ wrapperobj.GrpAccts = 1; } } } else if(grpAccMap == null || grpAccMap.isEmpty()){ wrapperobj.GrpAccts = 0; } if(Club == 'premierClub' && BTSList[0].RPoints__c != null && BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c != null && BTSList[0].Trip_Status_Eligibility__c!=null){ percentage = Integer.valueOf(((BTSList[0].RPoints__c)*100) / (BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c)); wrapperobj.tPoints = Integer.valueOf(BTSList[0].Trip_Status_Eligibility__r.Premier_Target_Points__c); } else if(Club == 'preferredClub' && BTSList[0].RPoints__c != null && BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c != null && BTSList[0].Trip_Status_Eligibility__c!=null){ percentage = Integer.valueOf(((BTSList[0].RPoints__c)*100) / (BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c)); wrapperobj.tPoints = Integer.valueOf(BTSList[0].Trip_Status_Eligibility__r.Preferred_Target_Points__c); } wrapperobj.rPoints = Integer.valueOf(BTSList[0].RPoints__c); wrapperobj.hasActive = BTSList[0].Trip_Status_Eligibility__r.Active__c; } wrapperobj.ViewRewards = userRec[0].ViewActivity__c; wrapperobj.perRewards= percentage; system.debug('wrapperobj' +wrapperobj); return wrapperobj; } public class demoWrapper { @AuraEnabled public Integer tPoints{get;set;} @AuraEnabled public Integer rPoints{get;set;} @AuraEnabled public Integer perRewards{get;set;} @AuraEnabled public Boolean ViewRewards{get;set;} @AuraEnabled public Boolean hasActive{get;set;} @AuraEnabled public Integer GrpAccts{get;set;} }
These lines are not covered by the above code.
for(Services__c servRec : serviceList ){ if((servRec.Account__r.CreatedDate >= grpcreatedStartDate) && (servRec.Account__r.CreatedDate <= grpcreatedEndDate)) { if(!grpAccMap.containsKey(servRec.Broker_of_Record__c)){ grpAccMap.put(servRec.Broker_of_Record__c, new Set<Id>()); } grpAccMap.get(servRec.Broker_of_Record__c).add(servRec.Account__c); } }
if(grpAccMap != null && ! grpAccMap.isEmpty()){ if(grpAccMap.get(accountIdstr) != null){ if(grpAccMap.get(accountIdstr).size() >= 2){ wrapperobj.GrpAccts = 2; } else if(grpAccMap.get(accountIdstr).size() ==1){ wrapperobj.GrpAccts = 1; } } }
- Raffus
- September 13, 2022
- Like
- 0
How to write a test class for below method
@AuraEnabled public static String loadData(String strCaseInfo) { System.debug('caseInfo ' + strCaseInfo); CaseInfoWrapper caseInfo = (CaseInfoWrapper)JSON.deserialize(strCaseInfo, CaseInfoWrapper.class); rand_App_Customer__c customer = getCustomerInfo2(caseInfo.emailId); Case cse = new Case(); cse.subject = 'tan One Problem Report'; cse.Origin = rand_APP; cse.Status = 'Awaiting Approval'; cse.Priority = 'Medium'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get(rand_APP).getRecordTypeId(); cse.Description = caseInfo.description; cse.rand_App_Customer__c = customer?.Id; cse.Issue_category__c = caseInfo.category; cse.Issue_Sub_Category__c = caseInfo.subCategory; insert cse; // for skip the triggers of ContentDocumentLink && ContentDocument ContentDocumentLinkTriggerUtil.skipTrigger = true; ContentDocumentTriggerUtil.skipTrigger = true; List<ContentVersion> cVersions = new List<ContentVersion>(); for (FileInfoWrapper file : caseInfo.files) { System.debug('fileInfo ' + file); if (String.isNotBlank(file.base64Data)) { ContentVersion cv = new ContentVersion(); cv.ContentLocation = 'S'; cv.PathOnClient = file.fileName; cv.VersionData = EncodingUtil.base64Decode(file.base64Data); cv.Title = file.fileName; cVersions.add(cv); } }
- Raffus
- September 07, 2022
- Like
- 0
How to get for loop covered in test method
How to cover a for loop in this below test method
@AuraEnabled public static string getCasesData(String caseId) { try { String query = 'SELECT Id,(SELECT Id, ContentDocumentId FROM ContentDocumentLinks), CaseNumber,Issue_category__c, Issue_Sub_Category__c, rand_App_Customer__r.Party_Id__c,rand_App_Customer__r.Customer_Mobile__c, Current_Location__Latitude__s, Current_Location__Longitude__s, LocationName__c, Owner.Name, Description,CreatedDate FROM Case WHERE Id =:caseId'; query += ' ORDER BY CreatedDate DESC LIMIT 1'; List<Case> cases = Database.query(query); CaseInfoWrapper caseInfo = new CaseInfoWrapper(); set<Id> contentDocId = new set<Id>(); for (Case caseRecord : cases) { caseInfo.description = caseRecord.Description; caseInfo.longitude = caseRecord.Current_Location__Latitude__s; caseInfo.latitude = caseRecord.Current_Location__Longitude__s; caseInfo.locationName = caseRecord.LocationName__c; caseInfo.category = caseRecord.Issue_category__c; caseInfo.subCategory = caseRecord.Issue_Sub_Category__c; caseInfo.partyId = caseRecord.rand_App_Customer__r.Party_Id__c; caseInfo.mobile = caseRecord.rand_App_Customer__r.Customer_Mobile__c; if (caseRecord.ContentDocumentLinks.size() > 0) { for (ContentDocumentLink cdl : caseRecord.ContentDocumentLinks) { contentDocId.add(cdl.ContentDocumentId); } } } list<id> contectVersionID = new list<id>(); map<Id, ContentDistribution> contectDMap = new map<Id, ContentDistribution>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentDocId ORDER BY CreatedDate ASC]) { contectVersionID.add(conDistribution.ContentDocumentId); contectDMap.put(conDistribution.ContentDocumentId, conDistribution); } list<FileInfoWrapper> fileInfo = new list<FileInfoWrapper>(); caseInfo.contentDocumentIds = contectVersionID; for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); } caseInfo.files = fileInfo; System.debug('caseInfo ##' + JSON.serialize(caseInfo)); return JSON.serialize(caseInfo); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }I have written the below test class
@IsTest public static void getCasesDataTest(){ Case caseInfo = new Case(); caseInfo.description = 'test'; caseInfo.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); insert caseInfo; ContentVersion contentVersion = new ContentVersion( Title = 'Penguins', PathOnClient = 'Penguins.jpg', VersionData = Blob.valueOf('Test Content'), IsMajorVersion = true ); insert contentVersion; List<ContentDocument> documents = [ SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument ]; //create ContentDocumentLink record ContentDocumentLink cdl = New ContentDocumentLink(); cdl.LinkedEntityId = caseInfo.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; insert cdl; randAppController.getCasesData(caseInfo.id); }But not covering the for loop that is
for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); }
- Raffus
- September 07, 2022
- Like
- 0
How to write a test method content document
@AuraEnabled
public static FileInfoWrapper createPublicUrl(String fileData) {
try {
FileInfoWrapper file = (FileInfoWrapper)JSON.deserialize(fileData, FileInfoWrapper.class);
if (String.isNotBlank(file.base64Data)) {
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = file.fileName;
cv.VersionData = EncodingUtil.base64Decode(file.base64Data);
cv.Title = file.fileName;
insert cv;
ContentDistribution cd = new ContentDistribution();
cd.Name = file.fileName;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowViewInBrowser = true;
cd.PreferencesLinkLatestVersion = true;
cd.PreferencesNotifyOnVisit = false;
cd.PreferencesPasswordRequired = false;
cd.PreferencesAllowOriginalDownload = true;
insert cd;
cd = [SELECT Id, ContentVersionId, ContentDownloadUrl FROM ContentDistribution WHERE Id = :cd.Id];
file.publicUrl = cd.ContentDownloadUrl;
file.contentDistributionId = cd.Id;
file.contentVersionId = cd.ContentVersionId;
return file;
}
else {
return file;
}
}
public static FileInfoWrapper createPublicUrl(String fileData) {
try {
FileInfoWrapper file = (FileInfoWrapper)JSON.deserialize(fileData, FileInfoWrapper.class);
if (String.isNotBlank(file.base64Data)) {
ContentVersion cv = new ContentVersion();
cv.ContentLocation = 'S';
cv.PathOnClient = file.fileName;
cv.VersionData = EncodingUtil.base64Decode(file.base64Data);
cv.Title = file.fileName;
insert cv;
ContentDistribution cd = new ContentDistribution();
cd.Name = file.fileName;
cd.ContentVersionId = cv.Id;
cd.PreferencesAllowViewInBrowser = true;
cd.PreferencesLinkLatestVersion = true;
cd.PreferencesNotifyOnVisit = false;
cd.PreferencesPasswordRequired = false;
cd.PreferencesAllowOriginalDownload = true;
insert cd;
cd = [SELECT Id, ContentVersionId, ContentDownloadUrl FROM ContentDistribution WHERE Id = :cd.Id];
file.publicUrl = cd.ContentDownloadUrl;
file.contentDistributionId = cd.Id;
file.contentVersionId = cd.ContentVersionId;
return file;
}
else {
return file;
}
}
- Raffus
- September 06, 2022
- Like
- 0
How to write test test method for below code
@AuraEnabled public static String loadData(String strCaseInfo) { System.debug('caseInfo ' + strCaseInfo); CaseInfoWrapper caseInfo = (CaseInfoWrapper)JSON.deserialize(strCaseInfo, CaseInfoWrapper.class); //rand_App_Customer__c customer = getCustomerInfo(caseInfo.partyId, caseInfo.mobile); rand_App_Customer__c customer = getCustomerInfo2(caseInfo.emailId); Case cse = new Case(); cse.subject = 'tan One Problem Report'; cse.Origin = rand_APP; cse.Status = 'Awaiting Approval'; cse.Priority = 'Medium'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get(rand_APP).getRecordTypeId(); // cse.Hex_Service_Request__c = 'System Update'; // cse.Hex_Service_Request_new__c = 'System Update'; // cse.ProblemCode__c = 'NOC for Name Addition - HO'; cse.Description = caseInfo.description; //RN Comment //cse.Current_Location__Latitude__s = caseInfo.latitude; //cse.Current_Location__Longitude__s = caseInfo.longitude; cse.rand_App_Customer__c = customer?.Id; //cse.LocationName__c = caseInfo.locationName; */ cse.Issue_category__c = caseInfo.category; cse.Issue_Sub_Category__c = caseInfo.subCategory; insert cse; // for skip the triggers of ContentDocumentLink && ContentDocument ContentDocumentLinkTriggerUtil.skipTrigger = true; ContentDocumentTriggerUtil.skipTrigger = true; List<ContentVersion> cVersions = new List<ContentVersion>(); for (FileInfoWrapper file : caseInfo.files) { System.debug('fileInfo ' + file); if (String.isNotBlank(file.base64Data)) { ContentVersion cv = new ContentVersion(); cv.ContentLocation = 'S'; cv.PathOnClient = file.fileName; cv.VersionData = EncodingUtil.base64Decode(file.base64Data); cv.Title = file.fileName; cVersions.add(cv); } } List<Id> contentDocumentIds = new List<Id>(caseInfo.contentDocumentIds); if (cVersions.size() > 0) { insert cVersions; List<ContentDistribution> ContentDistributionList = new List<ContentDistribution>(); for(ContentVersion ctv : cVersions){ ContentDistribution cd = new ContentDistribution(); cd.Name = ctv.Title; cd.ContentVersionId = ctv.Id; cd.PreferencesAllowViewInBrowser = true; cd.PreferencesLinkLatestVersion = true; cd.PreferencesNotifyOnVisit = false; cd.PreferencesPasswordRequired = false; cd.PreferencesAllowOriginalDownload = true; ContentDistributionList.add(cd); } if(ContentDistributionList.size() > 0){ INSERT ContentDistributionList; } Set<Id> cvIds = new Map<Id, ContentVersion>(cVersions).keySet(); for (ContentVersion cVersion : [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id IN:cvIds ORDER BY CreatedDate ASC]) { contentDocumentIds.add(cVersion.ContentDocumentId); } } List<ContentDocumentLink> links = new List<ContentDocumentLink>(); for (Id contentDocumentId : contentDocumentIds) { ContentDocumentLink link = new ContentDocumentLink(); link.LinkedEntityId = cse.Id; link.ContentDocumentId = contentDocumentId; link.ShareType = 'V'; links.add(link); } insert links; return [SELECT CaseNumber FROM Case WHERE Id = :cse.Id]?.CaseNumber; }Please help me to write a test method for the above method.
- Raffus
- September 06, 2022
- Like
- 0
How to write a test method for related objects
@AuraEnabled public static List<CaseResultWrapper> getCases(String emailid) { try { List<CaseResultWrapper> result = new List<CaseResultWrapper>(); List<String> caseStatuses = new List<String>{'Approved', 'Awaiting Approval', 'Rejected'}; String query = 'SELECT Id,CaseNumber, Issue_category__c, Points__c, Issue_Sub_Category__c, (SELECT Id, ContentDocumentId FROM ContentDocumentLinks WHERE ContentDocument.FileType != \'wav\'), Status, Country__c, Owner.Name, Description,CreatedDate FROM Case WHERE RecordType.DeveloperName= :rand_APP AND rand_App_Customer__r.Customer_Email__c !=null AND status IN :caseStatuses'; if (String.isNotBlank(emailid)) { query += ' AND rand_App_Customer__r.Customer_Email__c=:emailid'; } /*else if (String.isNotBlank(mobile)) { query += 'AND rand_App_Customer__r.Customer_Mobile__c=:mobile'; } else { query += 'AND Id = null'; }*/ query += ' ORDER BY CreatedDate DESC LIMIT 50'; //CreatedDate = THIS_QUARTER System.debug('getCases query '+query); List<Case> cases = Database.query(query); Map<Id, Case> contentCaseMap = new Map<Id, Case>(); for (Case caseRecord : cases) { if (caseRecord.ContentDocumentLinks.size() > 0 && caseRecord.ContentDocumentLinks[0].ContentDocumentId != null) { contentCaseMap.put(caseRecord.ContentDocumentLinks[0].ContentDocumentId, caseRecord); } else { contentCaseMap.put(caseRecord.Id, caseRecord); } } Map<Id, String> contentUrlMap = new Map<Id, String>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentCaseMap.keySet() ORDER BY CreatedDate ASC]) { contentUrlMap.put(conDistribution.ContentDocumentId, conDistribution.ContentDownloadUrl); } for (Id contentId : contentCaseMap.keySet()) { CaseResultWrapper caseWrp = new CaseResultWrapper(); caseWrp.contentDocId = contentId; caseWrp.caseRecord = contentCaseMap.get(contentId); caseWrp.imageUrl = contentUrlMap.get(contentId); caseWrp.categoryLogoUrl =''; DateTime dT = contentCaseMap.get(contentId).CreatedDate; If(dT.month()==1){ caseWrp.createdDate = dT.day()+'-Jan-'+dT.year(); } If(dT.month()==2){ caseWrp.createdDate = dT.day()+'-Feb-'+dT.year(); } If(dT.month()==3){ caseWrp.createdDate = dT.day()+'-Mar-'+dT.year(); } If(dT.month()==4){ caseWrp.createdDate = dT.day()+'-Apr-'+dT.year(); } If(dT.month()==5){ caseWrp.createdDate = dT.day()+'-May-'+dT.year(); } If(dT.month()==6){ caseWrp.createdDate = dT.day()+'-Jun-'+dT.year(); } If(dT.month()==7){ caseWrp.createdDate = dT.day()+'-Jul-'+dT.year(); } If(dT.month()==8){ caseWrp.createdDate = dT.day()+'-Aug-'+dT.year(); } If(dT.month()==9){ caseWrp.createdDate = dT.day()+'-Sep-'+dT.year(); } If(dT.month()==10){ caseWrp.createdDate = dT.day()+'-Oct-'+dT.year(); } If(dT.month()==11){ caseWrp.createdDate = dT.day()+'-Nov-'+dT.year(); } If(dT.month()==12){ caseWrp.createdDate = dT.day()+'-Dec-'+dT.year(); } result.add(caseWrp); } return result; }The parameter that i have passed that is email is not in case object but in rand_App_Customer__c object- and case child object of rand_App_Customer__c object- so how i can give the parameter for this method
Below is my test method
@IsTest public static void getCasesTest(){ // Id rand_AppRecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('rand_App').getRecordTypeId(); rand_App_Customer__c randCustomer = new rand_App_Customer__c(); randCustomer.Customer_ID__c = '1234567'; randCustomer.Customer_Email__c = 'tannow@tan.ae'; insert randCustomer; Case cse = new Case(); cse.Issue_Sub_Category__c = 'Test category'; cse.Status = 'Approved'; cse.Description = 'Test'; cse.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); cse.rand_App_Customer__c = randCustomer.Id; insert cse; List<ContentDocument> documents = [SELECT Id,title,LatestPublishedVersionId FROM ContentDocument]; ContentDocumentLink cdl = new ContentDocumentLink(); cdl.LinkedEntityId = cse.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; // cdl.FileType = 'jpg'; insert cdl; randAppController.getCases('tannow@tan.ae'); }
- Raffus
- September 05, 2022
- Like
- 0
How to write a test method for related objects with wrapper class in it.
I am not understanding what and how to put data for the below method
Please help...
@AuraEnabled public static string getCasesData(String caseId) { try { String query = 'SELECT Id,(SELECT Id, ContentDocumentId FROM ContentDocumentLinks), CaseNumber,Issue_category__c, Issue_Sub_Category__c, rand_App_Customer__r.Party_Id__c,rand_App_Customer__r.Customer_Mobile__c, Current_Location__Latitude__s, Current_Location__Longitude__s, LocationName__c, Owner.Name, Description,CreatedDate FROM Case WHERE Id =:caseId'; query += ' ORDER BY CreatedDate DESC LIMIT 1'; List<Case> cases = Database.query(query); CaseInfoWrapper caseInfo = new CaseInfoWrapper(); set<Id> contentDocId = new set<Id>(); for (Case caseRecord : cases) { caseInfo.description = caseRecord.Description; caseInfo.longitude = caseRecord.Current_Location__Latitude__s; caseInfo.latitude = caseRecord.Current_Location__Longitude__s; caseInfo.locationName = caseRecord.LocationName__c; caseInfo.category = caseRecord.Issue_category__c; caseInfo.subCategory = caseRecord.Issue_Sub_Category__c; caseInfo.partyId = caseRecord.rand_App_Customer__r.Party_Id__c; caseInfo.mobile = caseRecord.rand_App_Customer__r.Customer_Mobile__c; if (caseRecord.ContentDocumentLinks.size() > 0) { for (ContentDocumentLink cdl : caseRecord.ContentDocumentLinks) { contentDocId.add(cdl.ContentDocumentId); } } } list<id> contectVersionID = new list<id>(); map<Id, ContentDistribution> contectDMap = new map<Id, ContentDistribution>(); for (ContentDistribution conDistribution : [SELECT Id, ContentDocumentId, ContentDownloadUrl FROM ContentDistribution WHERE ContentDocumentId IN:contentDocId ORDER BY CreatedDate ASC]) { contectVersionID.add(conDistribution.ContentDocumentId); contectDMap.put(conDistribution.ContentDocumentId, conDistribution); } list<FileInfoWrapper> fileInfo = new list<FileInfoWrapper>(); caseInfo.contentDocumentIds = contectVersionID; for (ContentVersion cv : [SELECT Id, ContentDocumentId, FileExtension, FileType, PathOnClient, VersionData FROM ContentVersion WHERE ContentDocumentId IN:contectVersionID ORDER BY CreatedDate ASC]) { FileInfoWrapper fileData = new FileInfoWrapper(); fileData.base64Data = String.valueOf(cv.VersionData); fileData.contentVersionId = cv.Id; fileData.fileName = cv.PathOnClient; if (contectDMap.containsKey(cv.ContentDocumentId)) { fileData.publicUrl = contectDMap.get(cv.ContentDocumentId).ContentDownloadUrl; fileData.contentDistributionId = contectDMap.get(cv.ContentDocumentId).Id; } fileInfo.add(fileData); } caseInfo.files = fileInfo; System.debug('caseInfo ##' + JSON.serialize(caseInfo)); return JSON.serialize(caseInfo); } catch (Exception e) { throw new AuraHandledException(e.getMessage()); } }So far I have written below myself as per my understanding but it is not giving coverage after "for (Case case record : cases)".
@IsTest public static void getCasesDataTest(){ Case caseInfo = new Case(); caseInfo.description = 'test'; caseInfo.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByDeveloperName().get('rand_App').getRecordTypeId(); insert caseInfo; ContentVersion contentVersion = new ContentVersion( Title = 'Penguins', PathOnClient = 'Penguins.jpg', VersionData = Blob.valueOf('Test Content'), IsMajorVersion = true ); insert contentVersion; List<ContentDocument> documents = [ SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument ]; //create ContentDocumentLink record ContentDocumentLink cdl = New ContentDocumentLink(); cdl.LinkedEntityId = caseInfo.id; cdl.ContentDocumentId = documents[0].Id; cdl.shareType = 'V'; insert cdl; randAppController.CaseInfoWrapper wrapper= new randAppController.CaseInfoWrapper(); wrapper.category = 'Emaar Gift Card'; wrapper.subCategory = 'EGC - Card Error/Machine Network Failure'; wrapper.partyId = '1234'; wrapper.mobile = '7894561230'; randAppController.getCasesData('5003M038208iGzOLOU'); }
Please help...
- Raffus
- September 05, 2022
- Like
- 0
Aura component for updating the Status field of custom object.
I need to update the status(ak2397__Status__c) picklist field of the Custom Orders(ak2397__Orders__c) object using a lightning button. I have created a button 'cancel' and 'reorder'. If I click the cancel button then the status of the object should change from 'Ordered' to 'Cancelled' and if I click the reorder button then the status should change from 'Cancelled to 'Ordered'. I am stuck pls help.
Here is my complete code
Component----
Helper
Apex Controller
Here is my complete code
Component----
<aura:component controller="TestForOMapex" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" > <aura:attribute name="accList" type="List"/> <aura:attribute name="activeSections" type="List" /> <aura:attribute name="searchResult" type="List" description="use for store and display account list return from server"/> <aura:attribute name="searchKeyword" type="String" description="use for store user search input"/> <aura:handler name="init" value="{!this}" action="{!c.doinit}"/> <lightning:card title="Customer Order Details" iconName="standard:Contact"> <div class="slds-border_bottom"> </div> <div class="slds-scrollable_y"> <lightning:layoutItem size="12"> <div class="slds-text-longform"> <lightning:input value="{!v.searchKeyword}" placeholder="Search Customers" aura:id="searchField" name="searchField" onchange="{!c.onChange1 }"/> <br/> </div> </lightning:layoutItem> </div> <div class="slds-align_absolute-center"> <table class="slds-table slds-table_cell-buffer slds-table_bordered"> <thead> <tr class="slds-line-height_reset"> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order ID">Order ID</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Orders">Food Item</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Order Details</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Order Date</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order detail">Status</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Edit">Cancel</div> </th> <th class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Edit">ReOrder</div> </th> </tr> </thead> <br/> <tbody> <aura:iteration items="{!v.accList}" var="acc" indexVar="index"> <tr class="slds-line-height_reset"> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="FirstName">{!acc.ak2397__Order_Id__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Food Item"> {!acc.ak2397__Food_Item__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order Detail">{!acc.ak2397__Order_Details__c}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Order Date">{!acc.CreatedDate}</div> </td> <td class="slds-text-title_caps" scope="col"> <div class="slds-truncate" title="Status">{!acc.ak2397__Status__c}</div> </td> <td data-label="icon" class="slds-col slds-size_1-of-12" onclick="{!c.cancel}" id="{!acc.Id}"> <lightning:icon iconName="utility:delete" size="small" /> </td> <td data-label="icon" class="slds-col slds-size_1-of-12" onclick="{!c.reorder}" id="{!acc.Id}"> <lightning:icon iconName="utility:change_record_type" size="small" /> </td> </tr> </aura:iteration> </tbody> </table> </div> </lightning:card> </aura:component>Js Controller
({ onChange1: function (component, evt, helper) { var selectedLimit = component.find('searchField').get('v.value'); component.set('v.searchKeyword', selectedLimit); helper.SearchHelper(component, event); }, doinit: function(component) { var action = component.get('c.getContactData'); var self = this; action.setCallback(this, function(actionResult) { component.set('v.acclist', actionResult.getReturnValue()); }); $A.enqueueAction(action); }, cancel : function(component, event) { var action = component.get("c.cancelContact"); action.setParams({contactId:event.target.id}); action.setCallback(this, function(response) { component.set("v.accList",response.getReturnValue()); }); $A.enqueueAction(action); }, reorder : function(component, event) { var action = component.get("c.updateContact"); action.setParams({contactId:event.target.id}); action.setCallback(this, function(response) { component.set("v.accList",response.getReturnValue()); }); $A.enqueueAction(action); }, })
Helper
({ SearchHelper : function(component, event, helper) { var action = component.get('c.fetchAcc'); action.setParams({ searchKey : component.get("v.searchKeyword"), }); action.setCallback(this, function(response){ var state = response.getState(); if(state === "SUCCESS"){ var allValues = response.getReturnValue(); console.log("allValues--->>> " + JSON.stringify(allValues)); //component.set('v.activeSections', allValues.Name); component.set('v.accList', allValues); } else if(state === "ERROR") { var errors = response.getError(); if(errors){ if(errors[0] && errors[0].message){ console.log("Error Message: " + errors[0].message); } } else{ console.log("Unknown Error"); } } }); $A.enqueueAction(action); } });
Apex Controller
public class TestForOMapex { @AuraEnabled(cacheable=true) public static List<ak2397__Orders__c> fetchAcc (String searchKey){ String query= 'select ak2397__Order_Id__c, ak2397__Food_Item__c, ak2397__Order_Details__c, CreatedDate, ak2397__Status__c from ak2397__Orders__c'; if ( searchKey != Null ) { String key = '%' + searchKey + '%'; query += ' WHERE Name LIKE :key'; }system.debug(Database.query( query )); return Database.query( query ); } @AuraEnabled public static List<ak2397__Orders__c> getContactData(){ return [select Id from ak2397__Orders__c Limit 10]; } @AuraEnabled public static List<ak2397__Orders__c> cancelContact(String contactId) { List<ak2397__Orders__c> upContact = [SELECT Id, ak2397__Status__c FROM ak2397__Orders__c]; if(upContact.size()>0){ for(ak2397__Orders__c om: upContact){ om.ak2397__Status__c = 'Cancelled'; upContact.add(om); } upsert upContact; } return getContactData(); public static List<ak2397__Orders__c> updateContact(String contactId) { List<ak2397__Orders__c> upContact = [SELECT Id, ak2397__Status__c FROM ak2397__Orders__c]; if(upContact.size()>0){ for(ak2397__Orders__c om: upContact){ om.ak2397__Status__c = 'Ordered'; upContact.add(om); } upsert upContact; } return getContactData(); } } }
- Raffus
- July 05, 2022
- Like
- 0
Write a test class for this class for getting full coverage.
This UserMigrationRoute class is migration Community profile users to Partner profile users and saving their username Password in userMigration object. I have really hard time writing test classes. i have written Test class but don't know exactly how i can get full coverage. pls, help....
I am getting 65 percent coverage!
Line 48-77 is not covered (Boolean isSUccess=createUserMigration('',objUser[0],'');) to (return maprespone;)
Main class
Test class
I am getting 65 percent coverage!
Line 48-77 is not covered (Boolean isSUccess=createUserMigration('',objUser[0],'');) to (return maprespone;)
Main class
public class UserMigrationRoute extends BaseRoute{ public override Object doPost() { List<String> allowhosts=Label.Host_Name.split(','); Map<String,object> maprespone=new Map<String,object>(); system.debug('Hi'); if(String.isNotBlank(request.headers.get('Host')) && String.isNotBlank(request.headers.get('Host')) && !allowhosts.contains(request.headers.get('Host'))){ setResponseMessage('Invalid Host Header',ConstantsUtils.ERROR_CODE); return null; } if(this.request.headers.get('Content-Type')!=null && this.request.headers.get('Content-Type').substringAfter('/').equalsIgnoreCase('xml')){ setResponseMessage('Request in '+request.headers.get('Content-Type').substringAfter('/')+' format. Please provide request in json format.',ConstantsUtils.ERROR_CODE); return null; } map<String,object> data=this.getBodyJSON(); string id=(string)data.get('userId'); Map<String,String> mapofPartnerRecordType=new Map<String,String>(); List<User> objUser; try{ objUser=[SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null and id=:id]; if(objUser==null || objUser.size()==0){ setResponseMessage('Invalid uesrId, Please provide community user id',ConstantsUtils.ERROR_CODE); return null; } List<Account> lstAccount=new List<Account>(); if(!objUser[0].Account.IsPartner){ Account account=new Account(); account.Id=objUser[0].AccountId; account.IsPartner=true; lstAccount.add(account); // update lstAccount; //commented by shabnoor for testing } if(mapOfCustomerAndPartner.containsKey(objUser[0].profile.Name)){ String partnerProfile=mapOfCustomerAndPartner.get(objUser[0].profile.Name); objUser[0].ProfileId=[Select Id , Name from profile where Name= :partnerProfile].Id; } update objUser[0]; Boolean isSUccess=createUserMigration('',objUser[0],''); if(isSUccess){ maprespone.put('statuscode',1); maprespone.put('statusmessage','user migration successfully done'); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage','user migration failed'); return maprespone; } catch(DMLException ex){ if(ex.getDmlType(0)==StatusCode.DUPLICATE_USERNAME){ String charString = '!@#$%^&*()nopqrstuvwABCDPQRSTUVWXYZ0123456789abcdefghijkEFGHIJKLMNOlmxyz'; String randomNew = ''; while (randomNew .length() < 8){ Integer changeInt = Math.mod(Math.abs(Crypto.getRandomInteger()), charString.length()); randomNew += charString.substring(changeInt , changeInt +1); } Boolean isSUccess=createUserMigration(objUser[0].userName.replace('@',DateTime.now().millisecond() +'@'),objUser[0],randomNew); if(isSUccess){ system.setPassword(objUser[0].Id, randomNew); maprespone.put('statuscode',1); maprespone.put('statusmessage','user migration successfully done'); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); return maprespone; } maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); } catch(Exception ex){ maprespone.put('statuscode',0); maprespone.put('statusmessage',ex.getMessage()); return maprespone; } return maprespone; } public void setResponseMessage(String strMessge,String strCode){ response.addHeader('Content-Type', 'application/json'); response.responseBody = Blob.valueOf( '[{"message":' + strMessge + ',"errorCode":'+ strCode + '}]' ); response.statusCode = 400; } public Boolean createUserMigration(String Newusername,User objUser,String tempPassword){ try{ UserMigration__c UserMigration=new UserMigration__c(); // UserMigration.Newusername__c=objUser.userName; if(String.isNotBlank(Newusername)){ UserMigration.Newusername__c=Newusername; } UserMigration.OlduserName__c=objUser.userName; UserMigration.User__c=objUser.id; if(String.isNotBlank(tempPassword)){ UserMigration.tempPassword__c= tempPassword; } insert UserMigration; return true; }catch(Exception ex){ return false; } } public map<String,String> mapOfCustomerAndPartner=new Map<String,String>{ 'Customer Community - Admin'=>'Partner Community - Admin', 'Customer Community - Agent'=>'Partner Community - Agent', 'Customer Community - Agent + Admin'=>'Partner Community - Agent + Admin', 'Customer Community - Auth + Admin'=>'Partner Community - Auth + Admin', 'Customer Community - Auth + Admin + Agent'=>'Partner Community - Auth + Admin + Agent', 'Customer Community - Auth + Agent'=>'Partner Community - Auth + Agent', 'Customer Community - Auth Officer'=>'Partner Community - Auth Officer', 'Customer Community - Customer Direct User'=>'Partner Community - Customer Direct User', 'Customer Community - Owner'=>'Partner Community - Owner', 'Customer Community Plus User'=>'Partner Community - Admin', 'Customer Direct Guest'=>'Partner Direct Guest' }; }
Test class
public with sharing class UserMigrationRouteTest { @testSetup static void setup() { Broker_App_Settings__c BAS = new Broker_App_Settings__c( General_Partner_User_Id__c = '0054H0000067b6o', ApiToken__c = '6e9bece1914809fb8493146417e722f6', IVector__c = 'FFFFFFFFFFFFFFFF', Key__c = 'x/A%D*G-KaPdSgVkYp3s6v9y&B&E(H+M', General_Partner_User_Name__c = 'qaqqqqqqqqqqqqqq.com' ); insert BAS; TestDataSetup.createIntegrationCustomSettingsData(); TestDataSetup.createTriggerSettingsData(); TestDataSetup.createAppSettingsData(); Account partnerAccount = TestDataSetup.createAgencyAccount(); insert partnerAccount; Contact objAgencyContact = TestDataSetup.createAgentContact( partnerAccount.Id ); objAgencyContact.RERA_Card_No__c = '123456'; objAgencyContact.Sys_Agent_Representative__c = true; insert objAgencyContact; Profile portalProfile = [ SELECT Id FROM Profile WHERE Name = 'Sales Partner Community User' LIMIT 1 ]; User objPartnerUser = new User( Username = System.now().millisecond() + 'test999@test.com', ContactId = objAgencyContact.Id, ProfileId = portalProfile.Id, Alias = 'pTst', Email = 'testingisgoingon999@test.com', EmailEncodingKey = 'UTF-8', LastName = 'Con', CommunityNickname = 'test999', TimeZoneSidKey = 'America/Los_Angeles', LocaleSidKey = 'en_US', LanguageLocaleKey = 'en_US' ); Database.insert(objPartnerUser); } static testMethod void verifyContentType() { User objPartnerUser = [ SELECT Id, Username FROM User WHERE email = 'testingisgoingon999@test.com' ]; System.runAs(objPartnerUser) { String requestURI = '/userprofileupdate/'; String RESOURCE_PATH = '/services/apexrest' + requestURI; map<String, String> headers = new Map<String, String>(); headers.put('Content-Type', 'application/json'); headers.put('Host', 'www.gmail1.com'); Broker_App_Settings__c BAS = Broker_App_Settings__c.getOrgDefaults(); headers.put('apikey', BAS.ApiToken__c); Map<String, String> requestData = new Map<string, string>(); String JsonRecord = Json.serialize(requestData); setRestCall(RESOURCE_PATH, requestURI, 'POST', headers, null, JsonRecord); try { RestResponse resp = RestContext.Response; UserMigrationResource.handlePost(); resp = RestContext.Response; } catch (exception ex) { } } } static testMethod void createMigrationUserNegative(){ List<User> objUser = [SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null]; UserMigrationRoute mem = new UserMigrationRoute(); Boolean isSUccess = mem.createUserMigration('newusername123',objUser[0],'newpassword1234'); System.assertEquals(false,isSUccess, 'Result'); } static testMethod void createMigrationPositive(){ List<User> objUser = [SELECT Id,Profile.NAME,IsActive ,userName,AccountId,Account.IsPartner,IsPortalEnabled FROM User WHERE IsActive = TRUE and AccountId!=null]; UserMigrationRoute mem = new UserMigrationRoute(); Boolean isSUccess = mem.createUsermigration('',objUser[0],''); System.assertEquals(true,isSUccess,'result'); } static testMethod void verifydoPost() { User objPartnerUser = [ SELECT Id, Username FROM User WHERE email = 'testingisgoingon999@test.com' ]; System.runAs(objPartnerUser) { CaseTriggerHandler.TriggerDisabled = true; String requestURI = '///userprofileupdate/'; String RESOURCE_PATH = '/services/apexrest' + requestURI; map<String, String> headers = new Map<String, String>(); Broker_App_Settings__c BAS = Broker_App_Settings__c.getOrgDefaults(); headers.put('apikey', BAS.ApiToken__c); Map<String, String> requestData = new Map<string, string>(); requestData.put('userId', '0053M000001YvnTQAS'); String JsonRecord = Json.serialize(requestData); setRestCall(RESOURCE_PATH, requestURI, 'POST', headers, null, JsonRecord); try { RestResponse resp = RestContext.Response; UserMigrationResource.handlePost(); resp = RestContext.Response; //System.assertEquals(1,resp.statusCode,'success'); //Assert with expected status code. } catch (exception ex) { } } } public static void setRestCall( String resourcePath, String requestURI, String method, map<String, String> headers, map<String, String> paraMeters, String body ) { RestRequest req = new RestRequest(); req.requestURI = requestURI; req.resourcePath = resourcePath; req.httpMethod = method; if (String.isNotEmpty(body)) { req.requestBody = Blob.valueOf(body); } if (headers != null && headers.size() > 0) { req.headers.putAll(headers); } if (paraMeters != null && paraMeters.size() > 0) { req.params.putAll(paraMeters); } system.debug('test' + req); RestContext.Request = req; RestContext.Response = new RestResponse(); } }
- Raffus
- June 21, 2022
- Like
- 0