0

I have a test class which inserts partner user for testing. So, when I pass userinfor.getuserID(), it is returning null due to which my test class is failing with error

"System.NullPointerException: Attempt to de-reference a null object"

Below is the test class:

   @isTest (seeAllData=False)
private class KC_Reg_Handler_Test {
     @isTest (seeAllData=true)
    static void testPDRegistration() {
        Account acct = testDataGenerator.createTestAccount(); 
        update acct;
        Contact cont = testDataGenerator.createTestContact();

        String uniqueName = 'xyz@account.999888777.com';
        Auth.UserData dataX = new Auth.UserData('identifier', 'firstName', 'lastName', 'fullName', 'cat@gmail.com', 
            null, uniqueName, 'en', 'provider', null, null);

        Test.startTest();
        // PD Auth Provider Testing
        KC_RegHandler authP = new KC_RegHandler();
        User usr = authP.createUser(UserInfo.getUserId(), dataX);
        authP.updateUser(null, null, dataX);       

        // PD User Provisioning Web Service
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        req.requestURI = 'https://' + URL.getSalesforceBaseUrl().getHost() + '/services/apexrest/PD_AccountWS/0010';
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;

        PD_UserAccountWS.PD_UserAccountRequest pupr = new PD_UserAccountWS.PD_UserAccountRequest();
        pupr.Accountid = '111222333444';
        pupr.emailAddress = 'cat@mat.com';
        pupr.firstName = 'John';
        pupr.lastName = 'Account';
        pupr.language = 'en_US';
        PD_UserAccountWS.PD_UserAccountResponse upws = PD_UserAccountWS.doPost(pupr);

        pupr.Accountid = '111222333445';
        upws = PD_UserAccountWS.doPost(pupr);
        upws = PD_UserAccountWS.doPost(pupr);
        //
        req.httpMethod = 'GET';
        upws = PD_UserAccountWS.doGet();

        req.requestURI = 'https://' + URL.getSalesforceBaseUrl().getHost() + '/services/apexrest/PD_AccountWS';
        req.httpMethod = 'POST';
        RestContext.request = req;
        RestContext.response = res;
        upws = PD_UserAccountWS.doPost(pupr);
        req.httpMethod = 'GET';
        upws = PD_UserAccountWS.doGet();

        Test.stopTest();
    }



       @isTest (seeAllData=true)
    static void testPDRegistrationLocaleLangCheckErr() {
        Account acct = testDataGenerator.createTestAccount();                 
        Contact cont = testDataGenerator.createTestContact();

        String uniqueName = 'xyz@account.999888777.com';

        Auth.UserData dataX = new Auth.UserData('badidentifier', 'firstName', 'lastName', 'fullName', 'cat@gmail.com', 
            null, uniqueName, 'en', 'provider', null, null);

        Test.startTest();
        KC_RegHandler authP = new KC_RegHandler();    

        String provReq = '{"firstName": "Hugh", "lastName": "Man", "emailAddress": "abc@xyz.com", "language": "en_US", "locale": "en_US", "alias": null, "timeZone": null}';
        acct.Provision_Request__c = provReq;
        acct.Provision_Status__c = 'Active';

        update acct;
        User temp = authP.createUser(UserInfo.getUserId(), dataX); 
        system.debug('dataX'+dataX);
        system.debug('UserInfo.getUserId()'+UserInfo.getUserId());
        system.debug('temp'+temp) ;      
        User badLocaleLang = [SELECT Id, languagelocalekey, localesidkey, Contact.Account.Account_Request__c FROM User WHERE Id=:temp.Id LIMIT 1];
        system.debug('badLocaleLang '+badLocaleLang );        
        System.assertEquals(badLocaleLang.Contact.Account.Account_Request__c, provReq);
        System.assertEquals(badLocaleLang.languagelocalekey, 'en_US');
        System.assertEquals(badLocaleLang.localesidkey, 'en_US');

        Test.stopTest();
    }

}

Below is the createUser Method from Reg handler class

global User createUser(Id portalId, Auth.UserData data){
        if(!canCreateUser(data)) {
            //Returning null or throwing an exception fails the SSO flow
            return null;
        }
        User impersonatorUser = verifyImpersonator(data);
        if(impersonatorUser != null) {
            return impersonatorUser;
        }
        // Check if User is already present with Google Id
        list<User> usrList = [select Id from User where Contact.Account.Account_Id__c = :data.username and Contact.Account.Account_Status__c = 'Active' ORDER BY lastmodifieddate desc limit 1];
        if(usrList != null && usrList.size() > 0) {
            return usrList[0];
        }
        else {
            System.debug('IDX = ' + data.username);
            //The user is authorized, so create their Salesforce user
            list<Contact> con = [select Id, AccountId, Account.Account_Id_Format__c, Account.Account_Request__c from Contact 
                where Account.Account_Id__c =:data.username and Account.Account_Status__c = 'Active' limit 1];
            if(con != null && con.size() > 0) {
                User u = new User();
                Profile p = [SELECT Id FROM profile WHERE name='Paid Account'];


                String emailUser = data.email.split('@')[0];
                String emailDomain = data.email.split('@')[1];

                //TODO: Customize the username. Also check that the username doesn't already exist and
                //possibly ensure there are enough org licenses to create a user. Must be 80 characters or less.
                u.username = data.email;
                u.email = data.email;
                u.lastName = data.lastName;
                u.firstName = data.firstName;
                String alias = emailUser;
                //Alias must be 8 characters or less
                if(alias.length() > 8) {
                    alias = alias.substring(0, 8);
                }
                u.alias = alias;
                u.languagelocalekey = UserInfo.getLocale();
                u.localesidkey = UserInfo.getLocale();
                u.emailEncodingKey = 'UTF-8';
                u.timeZoneSidKey = 'America/Phoenix';
                u.profileId = p.Id;
                u.ContactId = con[0].Id;
                u.IsActive = true;
                u.CompanyName = 'Custom User';
                u.UserPreferencesHideS1BrowserUI = true;


                return u;
            }


        }
    }

Below is the stack trace

Class.KC_Reg_Handler_Test.testPDRegistrationLocaleLangCheckErr: line 87, column 1

I found that the issue is with userinfo.getuserid() and it is returning null value while inserting the user. Can anyone help me with it.

0

You are passing null manually in your code. See below:-

user  u = handler.createUser(null, sampleData);

This is why you are getting the issue. Here you have done correctly:-

kc_RegHandler authP = new kc_RegHandler();
User temp = authP.createUser(UserInfo.getUserId(), dataX);
  • Thanks Sanket The issue is with line temp as it is getting the null value. handle.createuser is working fine...whereas user temp = auth.createuser is throwing error. When I have debugged the code, i observed that userinfo.getuserid() is throwing error...Please suggest – Skumar Aug 9 at 6:46
  • can you edit your question and add debug statements too? Also the createUser method. – sanket kumar Aug 9 at 6:58
  • Hi @SanketKumar, I have updated my question. Could you please suggest any changes here. – Skumar Aug 13 at 10:30
0

Issue is resolved

The null pointer exception was due to Account record which was not getting inserted due to invalid Account ID field in createUser method. Due to that, as there is no partner account, the user record is not getting inserted in the test class. Found this issue by creating debug logs and going through the lines step by step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.