function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sumanth kumar 62sumanth kumar 62 

auto registration handler test class error

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.

Durga PaavanDurga Paavan
Hi Sumanth,

I see you are using seeAllData = true, Can you make it to seeAllData = false and check if the user creation is working or not.

Cheers!,
Durgapaavan
sumanth kumar 62sumanth kumar 62
Hi Durgapaavan,

Thanks for your concern on my issue.
I have set seeAllData to false but that didn't work. I am getting the same error irrespective of seeAllData condition.
Could you please suggest how to resolve this.

Thanks,
Sumanth Kumar
Durga PaavanDurga Paavan
Sumanth,

I see that insert statement for user creation is commented in above code. Can you confirm that you used insert statement for the creation?.

Cheers,
Durgapaavan
sumanth kumar 62sumanth kumar 62

No Durgapaavan. That method is working fine

The  issue is with "testPDRegistrationLocaleLangCheckChineseTrad" method where it is throwing error in line 46. That means, temp is returning null value in goodLocaleLang. 

Please suggest

Durga PaavanDurga Paavan
Can you check what this method is returning canCreateUser(data)?
sumanth kumar 62sumanth kumar 62
@DurgaPaavan,
Please find the createuser method below
 
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;
            }
        }
    }
I am recieving null from this method in  the code. THis is working fine in real time scenario whereas in test class, it is returning null.
Also, using userinfo.getuserid() returns my id. But here I am inserting communtiy user. Is that the reason for null pointer exception. Please suggest