• sumanth kumar 62
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 3
    Replies
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
private class KC_Reg_Handler_Test {
       @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();
    }

}

 From the above class, I found that createuser() method is returning null in the test class. It is working fine in real time scenario whereas it is returning null in test class.

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;

                try {
                    if(con[0].AccountId != null && con[0].Account.Account_Request__c != null) {
                        String jsonStr = con[0].Account.Account_Request__c;
                        PD_AccountUserWS.PD_AccountUserRequest pupr = (PD_AccountUserWS.PD_AccountUserRequest) JSON.deserialize (jsonStr,
                        PD_AccountUserWS.PD_AccountUserRequest.class);

                        if(pupr != null) {
                            if(pupr.locale != null) {
                                // Validate if stamped locale is valid, before trying to set it
                                Schema.DescribeFieldResult fieldResult = User.localesidkey.getDescribe();
                                List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();                                   
                                // If the locale is in the picklist, then set it
                                for (Schema.PicklistEntry pli : ple){
                                    if (pupr.locale.equals(pli.getValue())){
                                        u.localesidkey = pupr.locale;
                                    }
                                }
                            }
                            if(pupr.timezone != null) {
                                u.timeZoneSidKey = pupr.timezone;
                            }
                            if(pupr.language != null) {
                                // Validate if stamped language is valid, before trying to set it
                                Schema.DescribeFieldResult fieldResult = User.languagelocalekey.getDescribe();
                                List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();                                   

                                // Blindly try first 2 chars of language
                                String lng = pupr.language.substring(0,2);
                                for (Schema.PicklistEntry pli : ple){
                                    if (lng.equals(pli.getValue())){
                                        u.languagelocalekey = lng;
                                    }
                                }                                                                                                                   

                                // If the Language is in the picklist, then set it, potentially overriding the previous loop
                                // Handles cases like en_US, en_UK, en_CA, fr_CA, pt_BR, es_MX
                                for (Schema.PicklistEntry pli : ple){
                                    if (pupr.language.equals(pli.getValue())){
                                        u.languagelocalekey = pupr.language;
                                    }
                                }                                                                                 
                                if (!u.languagelocalekey.equals(pupr.language) && !u.languagelocalekey.equals(lng)){
                                    Key_Value_List__c tmp = Key_Value_List__c.getValues('PD_LanguageOverride_' + lng);
                                    if (tmp != null){
                                        String overrideLang = tmp.Value__c;
                                        for (Schema.PicklistEntry pli : ple){
                                            if (overrideLang.equals(pli.getValue())){
                                                u.languagelocalekey = overrideLang;
                                            }
                                        }                                                       
                                    }
                                }

                                // else do nothing, fallback to English                          
                            }
                        }
                    }
                } catch (Exception ex) {}

                insert u;

                String tmpStr = 'GROUP_' + u.Id;
                Group grpDL;
                list<Group> extGrp = [select Id from Group where DeveloperName=:tmpStr and Type='Regular' and Name like 'My Account %' limit 1];
                if(extGrp != null && extGrp.size() > 0) {
                    grpDL = extGrp[0];
                } 
                else {
                    grpDL = new Group(DeveloperName='GROUP_' + u.Id, 
                    DoesIncludeBosses=false, 
                    DoesSendEmailToMembers=false,
                    Name='My Account (' + con[0].Account.Account_Id_Format__c + ')', 
                    Type='Regular');
                    insert grpDL;
                }



                // Insert Chatter Group Members and User Shares
                if(groupDLMembers.size() > 0) {
                    Database.Saveresult[] sr = Database.insert(groupDLMembers, false);
                }

                chatterSetup(u.Id, grpDL.Id);
                return u;
            }
            else {
                return null;
            }
        }
    }

Below is the stack trace

Class.KC_Reg_Handler_Test.testPDRegistrationLocaleLangCheckErr: line 30, column 1
Can anyone help me with this?

Thanks,
SK
I have a test class which is as below
@isTest
private class KC_Reg_Handler_Test {
    static testMethod void testCreateAndUpdateUser() {

        KC_RegHandler handler = new KC_RegHandler ();
        Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
                                                     'testFirst testLast', 'testuse8888r@example.org', null, 'testuserlong', 'en_US', 'facebook',
                                                     null, new Map<String, String>{'language' => 'en_US'});

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

            // insert(u);
            //String uid = u.id;

            sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',
                                           'testNewFirst testNewLast', 'testnewuser@example.org', null, 'testnewuserlong', 'en_US', 'facebook',
                                           null, new Map<String, String>{});
            handler.updateUser(null, null, sampleData);
        }catch(Exception e){

        }
        // User updatedUser = [SELECT userName, email, firstName, lastName, alias FROM user WHERE id=:uid];

    }

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

    String uniqueName = 'xyz@newtest.666555444.com';
    Auth.UserData dataX= new Auth.UserData('goodidentifier', 'firstName', 'lastName', 'fullName', 'cat@newtest.com', 
        null, uniqueName, 'en', 'provider', null, null);        

    Test.startTest();
    // PD Auth Provider Testing
    kc_RegHandler authP = new kc_RegHandler();    

    acct.GoogleId__c = 'goodidentifier';      
    String AccReq = '{"timezone":null,"strId":"","locale":"es_EC","lastName":"","language":"zh_HK","googleId":"0","gmailAddress":"0@newtest.com","firstName":"","emailAddress":"0@newtest.com","customId":"0","alias":null}';
    acct.Account_Request__c = AccReq;
    acct.Account_Status__c = 'Active';
    update acct;
    User temp = authP.createUser(UserInfo.getUserId(), dataX);        
    User goodLocaleLang = [SELECT Id, languagelocalekey, localesidkey, Contact.Account.Account_Request__c FROM User WHERE Id=:temp.Id LIMIT 1];        
    System.assertEquals(goodLocaleLang.Contact.Account.Account_Request__c, AccReq);
    System.assertEquals(goodLocaleLang.languagelocalekey, 'zh_CN');
    System.assertEquals(goodLocaleLang.localesidkey, 'es_EC');

    Test.stopTest();
}
}

Code from Reg Handler Apex class:
global boolean canCreateUser(Auth.UserData data) {
        //TODO: Check whether we want to allow creation of a user with this data
        /*Set<String> s = new Set<String>{'brian@foreverliving.com.dev'};
        if(s.contains(data.username)) {
            return true;
        }
        return false;*/
        return true;
    }

    global User createUser(Id portalId, Auth.UserData data){
        if(!canCreateUser(data)) {
            //Returning null or throwing an exception fails the SSO flow
            return null;
        }
}


in the above code, I found that the user is not getting inserted and after running the test class, I am recieving null pointer exception. That means the user is not getting created/inserted at authP.CreateUser and auth.CanCreateUser These methods are creating users and when I have checked this null pointer, my code is not getting covered completely.
I have removed these methods but found that my code is covered to only 12%
Can anyone please help me out with this.

Hi,
I have a requirement where when the status of any Account in Salesforce is updated, the status of same account in the external system should be updated. I have integrated the 3rd party endpoint with Salesforce and I can able to do the update. Below is the code I've used to do so
public class AccUpdateController {
    @future(callout=true)
    public static void AccupdateController(Set<Id> accountIdset) {       
        string resultBodyGet = '';

        list<Account> accts = [SELECT Unique_ID__c, Account_Status__c, Email__c from Account where Account_Partner_Status__c = 'ACTIVE' and Id IN:accountIdset];

        system.debug('>>>>>>>>>>' + accts);        
        for(Account c : accts){         

            MAp<String, String> tags = new Map<String, String>();
            tags.put('accId', c.Unique_ID__c);
            tags.put('email', c.Email__c);
            tags.put('status', c.Account_Status__c);            
            system.debug('#### Input JSON: ' + JSON.serialize(tags));            
            try{
                string endpoint = 'https://my-endpoint.com';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endpoint);
                req.setMethod('POST');
                req.setHeader('Content-type', 'application/json');
                req.setbody(JSON.serialize(tags));
                Http http = new Http();
                system.debug('Sending User to update status');
                HTTPResponse response = http.send(req); 
                system.debug('Status updated');
                resultBodyGet = response.getBody();
                system.debug('Output response:' + resultBodyGet);
                accResponse myAccResponse = new accResponse();
                myAccResponse = (accResponse) JSON.deserialize(resultBodyGet, accResponse.class);
                system.debug('#### myAccResponse: ' + myAccResponse);

            }
            catch (exception e) {                              
            }   
        }
    }    
    public class accResponse {
        public string message {get;set;}
    }
}

Now I need to send jwt token as a part of my body to recieve the status as success. Can anyone guide me how to do so as I do not have fair bit of idea on  how to generate JWT token in Salesforce

Thanks in advance,
SK
I have a test class which is as below
@isTest
private class KC_Reg_Handler_Test {
    static testMethod void testCreateAndUpdateUser() {

        KC_RegHandler handler = new KC_RegHandler ();
        Auth.UserData sampleData = new Auth.UserData('testId', 'testFirst', 'testLast',
                                                     'testFirst testLast', 'testuse8888r@example.org', null, 'testuserlong', 'en_US', 'facebook',
                                                     null, new Map<String, String>{'language' => 'en_US'});

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

            // insert(u);
            //String uid = u.id;

            sampleData = new Auth.UserData('testNewId', 'testNewFirst', 'testNewLast',
                                           'testNewFirst testNewLast', 'testnewuser@example.org', null, 'testnewuserlong', 'en_US', 'facebook',
                                           null, new Map<String, String>{});
            handler.updateUser(null, null, sampleData);
        }catch(Exception e){

        }
        // User updatedUser = [SELECT userName, email, firstName, lastName, alias FROM user WHERE id=:uid];

    }

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

    String uniqueName = 'xyz@newtest.666555444.com';
    Auth.UserData dataX= new Auth.UserData('goodidentifier', 'firstName', 'lastName', 'fullName', 'cat@newtest.com', 
        null, uniqueName, 'en', 'provider', null, null);        

    Test.startTest();
    // PD Auth Provider Testing
    kc_RegHandler authP = new kc_RegHandler();    

    acct.GoogleId__c = 'goodidentifier';      
    String AccReq = '{"timezone":null,"strId":"","locale":"es_EC","lastName":"","language":"zh_HK","googleId":"0","gmailAddress":"0@newtest.com","firstName":"","emailAddress":"0@newtest.com","customId":"0","alias":null}';
    acct.Account_Request__c = AccReq;
    acct.Account_Status__c = 'Active';
    update acct;
    User temp = authP.createUser(UserInfo.getUserId(), dataX);        
    User goodLocaleLang = [SELECT Id, languagelocalekey, localesidkey, Contact.Account.Account_Request__c FROM User WHERE Id=:temp.Id LIMIT 1];        
    System.assertEquals(goodLocaleLang.Contact.Account.Account_Request__c, AccReq);
    System.assertEquals(goodLocaleLang.languagelocalekey, 'zh_CN');
    System.assertEquals(goodLocaleLang.localesidkey, 'es_EC');

    Test.stopTest();
}
}

Code from Reg Handler Apex class:
global boolean canCreateUser(Auth.UserData data) {
        //TODO: Check whether we want to allow creation of a user with this data
        /*Set<String> s = new Set<String>{'brian@foreverliving.com.dev'};
        if(s.contains(data.username)) {
            return true;
        }
        return false;*/
        return true;
    }

    global User createUser(Id portalId, Auth.UserData data){
        if(!canCreateUser(data)) {
            //Returning null or throwing an exception fails the SSO flow
            return null;
        }
}


in the above code, I found that the user is not getting inserted and after running the test class, I am recieving null pointer exception. That means the user is not getting created/inserted at authP.CreateUser and auth.CanCreateUser These methods are creating users and when I have checked this null pointer, my code is not getting covered completely.
I have removed these methods but found that my code is covered to only 12%
Can anyone please help me out with this.