You need to sign in to do that
Don't have an account?
Raffus
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(); } }
Priya (Salesforce Developers)
The developer community recommends providing any attempts/code you've started, any errors you're getting, or where exactly you're struggling in achieving this while posting a question.
Raffus
So what you are seeing above is my attempt/code and the coverage is the issue that even I am not understanding, that is why just asking for guidance. So try to understand others' queries while posting, otherwise, no need to comment.