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
sarika12sarika12 

Test class causing coverage issue for class

Hi all, I'm new to salesforce development. I'm trying to write test class for Registartion handler class and it didn't give me full coverage even after multiple changes.

Apex class:

global class RegistrationHandlerSSO implements Auth.RegistrationHandler {

    global User createUser(Id portalId, Auth.UserData data) {

        //Querying all users
        List<User> userList = new List<User>([
            SELECT  Id
            FROM    User
            WHERE   Id =: data.attributeMap.get('alt_username') AND
                    IsActive = true and
                    SFDC_License_Type__c = 'Customer Community Plus Login'
        ]);

        User uId;
        boolean generateUser = true;

        for (User u:userList) {

            //Checking that current user is already there in system or not.
            //If yes, performing below operations
            if (u.Id == data.attributeMap.get('alt_username')) {

                Id userIds= u.Id;

                //Fetch ThirdPartyAccountLink records associated with this user and delete it using
                // Auth.AuthToken.revokeAccess() method
                List<ThirdPartyAccountLink> thirdPartyActLink = new List<ThirdPartyAccountLink>(
                    [SELECT Handle, Provider, SsoProviderName, UserId, ThirdPartyAccountLinkKey,
                            user.contact.Account.Id, remoteIdentifier, SsoProvider.id
                     FROM   ThirdPartyAccountLink
                     WHERE  UserId =: userIds
                     LIMIT  1]);

                if(!thirdPartyActLink.isEmpty())
                Auth.AuthToken.revokeAccess(
                            thirdPartyActLink[0].SsoProvider.id,
                            thirdPartyActLink[0].Provider,
                            thirdPartyActLink[0].UserId,
                            thirdPartyActLink[0].remoteIdentifier
                        );

                //Marking this boolean as false to avoid creating new user
                generateUser = false;

                //if user is aleadythere in system paas it to updateUser() method to avoid linking
                // Id change
                updateUser(u.Id, portalId, data);
                uId = u;
            }
        }

        return(uId);
    }

    global void updateUser(Id userId, Id portalId, Auth.UserData data) {

        // checking for ID whether it same as logged in community user. if not then update it
        if(userId != data.attributeMap.get('alt_username')) {
            userId = data.attributeMap.get('alt_username');
        }

        List<User> userList = new List<User>([
            SELECT  Id
            FROM    User
            WHERE   Id =: userId
        ]);

        for (User u:userList) {

            List<ThirdPartyAccountLink> thirdPartyActLink = new List<ThirdPartyAccountLink>(
                    [SELECT Handle, Provider, SsoProviderName, UserId, ThirdPartyAccountLinkKey,
                            user.contact.Account.Id, remoteIdentifier, SsoProvider.id
                     FROM   ThirdPartyAccountLink
                     WHERE  UserId =: u.Id
                     LIMIT  1]);

                if(!thirdPartyActLink.isEmpty()) {
                    try {
                        Auth.AuthToken.revokeAccess(
                            thirdPartyActLink[0].SsoProvider.id,
                            thirdPartyActLink[0].Provider,
                            thirdPartyActLink[0].UserId,
                            thirdPartyActLink[0].remoteIdentifier
                        );
                    } catch (System.DmlException e) {
                        System.debug('@@@Error while deleteImmediate::'+e);
                        System.Debug('Cause: ' + e.getCause());
                        System.Debug('TypeName: ' + e.getTypeName());
                        System.Debug('getDmlFieldNames: ' + e.getDmlFieldNames(0));
                        System.Debug('getDmlFields: ' + e.getDmlFields(0));
                        System.Debug('getDmlId: ' + e.getDmlId(0));
                        System.Debug('getDmlMessage: ' + e.getDmlMessage(0));
                        System.Debug('getDmlType: ' + e.getDmlType(0));
                        System.Debug('getNumDml: ' + e.getNumDml());
                        System.Debug('Message: ' + e.getMessage());
                    }
                }

                User u2 = new User(id=u.Id);
                update(u2);
        }
    }
}

I wrote below test class for this which is giving me only 32% coverage:
@isTest
private class RegistrationHandlerSSOTest {
    static testMethod void testCreateUser() {

        Profile pf= [Select Id from profile where Name='System Administrator'];

        RegistrationHandlerSSO handler = new RegistrationHandlerSSO();

        Auth.UserData userData = new Auth.UserData (
                                                   'testId', 'testFirst', 'testLast',
                                                   'testFirst testLast', 'testuse8888r@example.org',
                                                   null, 'testuse8888r@example.org', 'en_US',
                                                   'facebook', null,
                                                   new Map<String, String>{'language' => 'en_US'}
                                                   );
        User u1 = new User (
            				firstname = 'testFirst',
                            lastName = 'testLast',
                            email = 'testuse8888r@example.org',
                            Username = 'testuse8888r@example.org',
                            EmailEncodingKey = 'ISO-8859-1',
                            Alias = 'teste8r',
                            TimeZoneSidKey = 'America/Los_Angeles',
                            LocaleSidKey = 'en_US',
                            LanguageLocaleKey = 'en_US',
                            ProfileId = pf.Id
                            );
        insert u1;

        try {
            User u = handler.createUser(null, userData);
		}
        catch(Exception e) {
            System.debug('Error: '+e);
        }
    }
    
    static testMethod void testUpdateUser() {

        Profile pf= [Select Id from profile where Name='System Administrator'];

        User u1 = new User (
                            firstname = 'testFirst',
                            lastName = 'testLast',
                            email = 'testuse8888r@example.org',
                            Username = 'testuse8888r@example.org',
                            EmailEncodingKey = 'ISO-8859-1',
                            Alias = 'teste8r',
                            TimeZoneSidKey = 'America/Los_Angeles',
                            LocaleSidKey = 'en_US',
                            LanguageLocaleKey = 'en_US',
                            ProfileId = pf.Id
                            );
        insert u1;

        RegistrationHandlerSSO handler = new RegistrationHandlerSSO();

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

        try {
            UserData = new Auth.UserData (
                                         'testNewId', 'testNewFirst', 'testNewLast',
                                         'testNewFirst testNewLast', 'testnewuser@example.org',
                                         null, 'testnewuserlong', 'en_US', 'facebook',
                                         null, new Map<String, String>{}
                                         );
            handler.updateUser(u1.Id, null, userData);
        }
        catch(Exception e) {
            System.debug('Error: '+e);
        }
    }
}

Can someone please suggest me how to enough coverage to deploy this in prod?

Thanks in advance.
AbhishekAbhishek (Salesforce Developers) 
Code coverage is a measurement of how many unique lines of your code are executed while the automated tests are running. Code coverage percentage is the number of covered lines divided by the sum of the number of covered lines and uncovered lines.

For purposes of calculating code coverage, only executable lines of code are counted, whether covered or uncovered. Comments and blank lines are not counted, and System.debug() statements and curly braces that appear alone on one line are also not counted.

While writing unit tests, the main emphasis should be given on actually testing the logic and behavior of the block by designing input data to ensure the code path executes and writing assertions to make sure the code's behavior is as expected. Code coverage is a side effect of this testing process.
Fundamentally, to increase your code coverage, you must write functional unit tests for code paths that are not currently covered. For more community resources on writing high-quality unit tests

Go through the below blog which will guide you how to write the test class easily,

https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.